CSS Modules

Posted on

in

CSS modules allow you to create unique class names even when the class is already used in another file. Name the file like so: name.module.css. Right normal css in it. Import the file like so:

import styles from './Name.module.css'

Apply it to an element like so:

<div className={styles.testClass}>test</div>

where testClass is a class specified in your css module file. When the html file is rendered it will look something like this:

<div class="Name_testClass__3h_do">test</div>

Styling children

You can use nesting in CSS modules like so:

.testClass {
    background: red;
    color: blue;
    .child {
        background: yellow;
    }
}

.child {
    color: green;
}

and here is some example HTML:

<div className={styles.testClass}>
   <span className={styles.child}>test</span>
</div>
<span className={styles.child}>not a child</span>

In this example, the actual child will have both styles while the non child will only get the style of green text.

Global css

You can add “normal” css like so:

:global(.col){
    background: green;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031