Vite JS Tutorial: CSS Modules 🎯

beginner
9 min

Vite JS Tutorial: CSS Modules 🎯

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!

What are CSS Modules? 📝

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.

Setting up CSS Modules with Vite 💡

  1. First, make sure you have a Vite project set up:
npm create vite-app my-app cd my-app
  1. To use CSS Modules, you'll simply create a .module.css file alongside your JavaScript component.
src/ App.js App.module.css

Basic CSS Modules Example 🎯

Let's create a simple component and its corresponding CSS Module.

App.js:

javascript
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:

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.

Importing CSS Modules 📝

You can import CSS Modules just like any other CSS file, but with the .module extension.

javascript
import './App.module.css';

Naming Conventions for CSS Modules 💡

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:

css
:local(.container) { display: flex; flex-direction: column; align-items: center; } :local(.title) { font-size: 2rem; color: cornflowerblue; }

Styling Multiple Components with CSS Modules 🎯

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:

css
.button { padding: 10px; border-radius: 5px; background-color: dodgerblue; color: white; }

AnotherComponent.js:

javascript
import React from 'react'; import styles from './App.module.css'; function AnotherComponent() { return ( <button className={styles.button}>Click me!</button> ); } export default AnotherComponent;

Quiz 📝

Quick Quiz
Question 1 of 1

What does CSS Modules do for you in Vite projects?

Wrapping Up 🎯

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! 🎉