skip to Main Content

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. 1. Import the global CSS like this:

    import './index.css'
    

    2. Change the element to:

    <div className={`${styles.Container} danger-container `}>Hello world</div>
    

    from:

    <div className={`${styles.Container} ${className}`}>Hello world</div>
    
    Login or Signup to reply.
  2. 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:

    .danger-container {/* 0,1,0 */
        background-color: red;
    }
    
    .Container.danger-container {/* 0,2,0 */
        background-color: blue;
    }
    
    body .danger-container[class] {/* 0,2,1 */
        background-color: pink;
    }
    
    .Container {/* 0,1,0 */
        background-color: green;
    }
    <div class='Container danger-container'>Hello world</div>

    Another way would be to give your element an ID since ID’s trump classes in terms of specificity.

    #danger-container {/* 1,0,0 */
        background-color: orange;
    }
    
    .Container {/* 0,1,0 */
        background-color: green;
    }
    <div class='Container' id='danger-container'>Hello world</div>

    Some resources to help you learn about CSS Specificity:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search