I’m struggling to find a solution to this simple problem. I have a component which I, by default, style using a class from a *.module.css
file. However, I want to override this style with one from a global stylesheet but I am failing to achieve this.
See example below:
// HelloWorld.tsx
import styles from './HelloWorld.module.css
export default function HelloWorld({className}) {
return <div className={`${styles.Container} ${className}`}>Hello world</div>;
}
/* HelloWorld.module.css */
.Container {
background-color: green; /* a default style for the component to be overridden by users */
}
/* global.css */
.danger-container {
background-color: red;
}
I then want to use the component as follows:
<HelloWorld className='danger-container' />
but the local style is not being overridden and the container remains green.
As mentioned, the reason I would like to do this is because I am creating a styled UI library and would like to provide a default style that users can then override.
The only way I can override it is using !important
but I have been told that it is bad practice to do this and would rather the users of the library not have to use !important
to override my default styles.
Please assist me on what the best way to go about this is.
Thank you in advance.
2
Answers
1. Import the global CSS like this:
2. Change the element to:
from:
Your two CSS statement have the same level of specificity so whichever statement comes last in the cascade wins. In your case this is the
.Container
. If you want.danger-container
to override.Container
then you will need for it to be more specific. There are several ways to do this. Here are a few:Another way would be to give your element an
ID
since ID’s trump classes in terms of specificity.Some resources to help you learn about CSS Specificity: