How to override style of Library components while using CSS Modules?

8.4k views Asked by At

I'm using NextJS, which use CSS Module, I want to use some CSS Library likes Material UI, ... But how to override style of components that I import from those Library?..

3

There are 3 answers

0
DucHT On

After read documents from https://github.com/css-modules/css-modules .Seriously, it's quite simple, just use :global scope. Ex:

.className :global(.lib-component-classname){
  // Style here apply to component that's imported from libs
}
1
wilbo On

You can always use the !important suffix after your style rule, but thats not really recommended because it goes against the Cascading of your Style Sheets (CSS).

What worked for me is using the :global selector, like DucHT explained, like this:

:global(li.ant-menu-item).siderMenuItem {
  display: flex;
  align-items: center;
  padding-top: 26px;
  padding-bottom: 26px;
}
0
Tom S On

Building on @DucHT's answer, for people like me who really prefer it spelled out totally:

// MyComponent.tsx:

import LibraryComponent from 'some-library'
import styles from './MyComponent.module.scss'

export default function MyComponent({}) {
  return (
    <div>
      <LibraryComponent className={styles.classNameICanChoose} />
    </div>
  )
}

// MyComponent.module.scss:

.classNameICanChoose :global(.lib-component-classname){
  // Style here apply to component that's imported from libs
  // will overwrite .lib-component-classname
}