Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 219
Chris Avatar asked Aug 28 '18 09:08

Chris


People also ask

How do you override CSS in Reactjs?

To override a style, you have two options. Either you can pass a style object, or you can pass a function that will obtain props regarding the current internal state of the component, thus enabling you to modify styles dynamically depending on the component state, such as isError or isSelected .

Can I use CSS modules with material UI?

If you love using Styled-Components or CSS modules, you have the freedom to use it with Material UI. In my opinion, this sort of flexibility is very important to widen the usage of a styling library. There are a few things you should keep in mind if you are combining JSS based styling with Material UI.


1 Answers

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.

like image 135
Chris Avatar answered Oct 06 '22 01:10

Chris