Search code examples
reactjscss-modules

Dealing with stylesheet order and css module className overrides


I have a component that has its own style, e.g.

.prompt { color: red; }

It's declared as so:

import cn from 'classnames';
import styles from './styles.css';

const MyComponent = ({className}) => {
  return (
    <div className={cn(styles.prompt, className)}>
      test
    </div>
  );
}

In my specific use case, the stylesheet for the className being passed in is actually defined and added to the head BEFORE the stylesheet from the module, so the module's css always overrides the style of the className being passed in. Something like:

enter image description here

Notice the background: yellow from second class is being overridden by the background from the module's own class.

Other than using !important in the secondary class, how can I work around this?


Solution

  • Based on Mr. Lister's response, I re-evaluated my existing knowledge of specificity and came up with the following solution in the higher level css:

    // in app.scss
    .offline.prompt {
        color: red;
    }
    
    // in app.tsx
    const classes = cn(Styles.offline, Styles.prompt);
    return <OfflineApp className={classes}>...</OfflineApp>;
    

    Essentially, I just tag the module markup with another sibling class to increase specificity and target the necessary properties using that. WAY better than abusing !important.