A goal of modular CSS is to scope styles to components. Globally styling
elements like h1 is to be done sparingly. Instead, we use class syntax:
/* Component.module.css */
.header {
color: purple;
}
// Component.tsx
import {styles} from './Component.module.css';
const Component = () => {
return (
<section>
<h1 className={styles.header}>A purple header here π</h1>
</section>
);
};
This keeps the header styles just on this element, in this component. But, we can still style elements:
/* Component.module.css */
.section h1 {
color: purple;
}
Nesting h1 in a class means that our CSS is compiled to something like this:
._section_1hpv5_1 h1 {
color: purple;
}
The purple color only applies to our targeted h1 via standard cascading.
Now, we don’t need a class on the header, which I think promotes a readable stylesheet as the component grows.
// Component.tsx
import {styles} from './Component.module.css';
const Component = () => {
return (
<section className={styles.section}>
<h1>A purple header here π</h1>
</section>
);
};