Go back

CSS modules

Let's see how can we split styles into modules. I will show you how I do it in React and vanilla CSS.

Vanilla CSS

Needs to be a folder called styles, in which all CSS files will be. There is index.css, inside it can look like this:

@import "./colors.css";
@import "./settings.css";
@import "./navbar.css";
@import "./page.css";
@import "./feed.css";
@import "./content.css";
@import "./darktheme.css";
@import "./footer.css";
@import "./categoryPage.css";
@import "./article.css";

Here we import all .css files. So, you just need to create a .css file in which you write styles as usual, and then just import it in index.css, THAT'S IT.

React

In React you can use .module.css files and import them already in components:

import React from "react";
import s from "../../styles/homePage/hero.module.css";

const Hero = () => {
   return (
      <div className={s.main}>
         <div className={s.tagline}>
            <h1>Hello :)</h1>
            <p>Suimiro blog</p>
         </div>
      </div>
   );
};

export default Hero;

It's basic React component. 's' in import s from '...' is just a variable (can be any name), which you will then need to specify in the className element.

className={s.tagline}

tagline it's class name in hero.module.css.

.main .tagline {
   display: flex;
   flex-direction: column;
   ...;
}

Conclusion

Nothing complicated in these two options. In CSS you just need to do @import, and in React import s from '...'.

Note: In React final version of class name will be something like this: hero_tagline__K9D64, React makes it so that this class is always unique and does not mix styles with other classes.

June 27, 2022

Go back