Welcome to this in-depth guide on CSS Modules using Vite JS! By the end of this lesson, you'll be able to leverage CSS Modules to keep your CSS organized, reusable, and maintainable in your Vite projects. Let's get started!
CSS Modules is a feature provided by React, but you can use it in any JavaScript project. It allows you to create encapsulated CSS styles that are scoped to individual components. This means your CSS styles won't leak into other components, improving the maintainability and readability of your codebase.
npm create vite-app my-app
cd my-app
.module.css file alongside your JavaScript component.src/
App.js
App.module.css
Let's create a simple component and its corresponding CSS Module.
App.js:
import React from 'react';
import styles from './App.module.css';
function App() {
return (
<div className={styles.container}>
<h1 className={styles.title}>Welcome to CodeYourCraft!</h1>
</div>
);
}
export default App;App.module.css:
.container {
display: flex;
flex-direction: column;
align-items: center;
}
.title {
font-size: 2rem;
color: cornflowerblue;
}Now, if you run the app, you should see the title styled as specified in the CSS Module.
You can import CSS Modules just like any other CSS file, but with the .module extension.
import './App.module.css';In CSS Modules, class names are converted to camelCase by default. If you prefer to use kebab-case or another naming convention, you can use a custom :local(...) syntax.
App.module.css:
:local(.container) {
display: flex;
flex-direction: column;
align-items: center;
}
:local(.title) {
font-size: 2rem;
color: cornflowerblue;
}You can style multiple components by defining classes at the root of your CSS Module. However, remember that CSS Modules are scoped to their respective components, so styles will not leak to other components.
App.module.css:
.button {
padding: 10px;
border-radius: 5px;
background-color: dodgerblue;
color: white;
}AnotherComponent.js:
import React from 'react';
import styles from './App.module.css';
function AnotherComponent() {
return (
<button className={styles.button}>Click me!</button>
);
}
export default AnotherComponent;What does CSS Modules do for you in Vite projects?
In this guide, you learned about CSS Modules, how to set them up in a Vite project, and explored some practical examples. With CSS Modules, you can write clean, organized, and reusable CSS that won't conflict with other components in your project. Happy coding! 🎉