As frontend applications grow, managing CSS becomes increasingly challenging. A small website may contain only a few pages and a limited number of stylesheets. A large application, however, can contain hundreds of components, multiple developers, shared design systems, reusable layouts, and thousands of CSS declarations. Without a well-organized styling strategy, styles can become difficult to maintain, debug, and extend.
One common problem in traditional CSS development is the global scope of class names. A class named .card, .button, .header, or .container can unintentionally affect elements in different parts of an application if the same selector is reused. A change made to one stylesheet may unexpectedly alter another component. This creates CSS conflicts that become harder to identify as a project expands.
CSS Modules address this problem by providing locally scoped class names. Instead of treating every class name as globally available, CSS Modules allow styles to be associated with individual components or modules. During the build process, class names are transformed into unique identifiers, reducing the possibility of accidental conflicts.
CSS Modules are widely useful in component-based frontend development, particularly in React and frameworks such as Next.js. They help developers organize styles alongside components, reuse familiar CSS syntax, and maintain a clear separation between different parts of an application.
This article explains CSS Modules from the fundamentals to practical implementation. It covers local scoping, global styles, composition, dynamic styling, React integration, Next.js usage, naming conventions, architecture, performance considerations, accessibility, common mistakes, and a practical project.
Continue Reading
1. Understanding the Problems with Traditional CSS
Traditional CSS uses global selectors by default. When a stylesheet defines a class, that class can match any element in the document that uses the same name.
Consider the following stylesheet:
.card {
padding: 20px;
background: white;
border-radius: 10px;
}
.button {
background: blue;
color: white;
}
.header {
padding: 24px;
}These selectors are not automatically limited to a particular component. If another stylesheet defines .card with different properties, the final appearance may depend on stylesheet order, selector specificity, and the cascade.
Imagine a project containing a product card, a profile card, and a dashboard card. All three components might use the class name .card, but each may need different styling.
A developer might attempt to solve this through increasingly specific selectors.
.product-section .card {
background: white;
}
.profile-section .card {
background: #eff6ff;
}
.dashboard-section .card {
background: #f8fafc;
}Although this can work, the stylesheet becomes more dependent on document structure. Moving a component to another section may require changing its selectors.
Another common approach is to create long and unique class names.
.product-page-product-card {
padding: 20px;
}
.user-profile-information-card {
padding: 24px;
}
.admin-dashboard-statistics-card {
padding: 18px;
}This reduces some naming conflicts but creates naming overhead. Developers must manually maintain naming conventions across the entire project.
CSS Modules offer a different solution by automatically generating scoped class names during the build process.
2. What Are CSS Modules?
CSS Modules are CSS files in which class names and animation names are treated as locally scoped by default. A build tool processes these files and transforms their local identifiers into unique generated names.
For example, a file named Card.module.css may contain:
.card {
padding: 20px;
background: white;
border-radius: 10px;
}A build system can transform the class name into something similar to:
.Card_card__a8f3k {
padding: 20px;
background: white;
border-radius: 10px;
}The generated name is illustrative. The actual format depends on the build tool and its configuration.
The important point is that the original .card class is no longer treated as an unrestricted global class. The component imports the CSS Module and receives a mapping between the original class name and its generated identifier.
This means two components can independently define a class named .card without unintentionally sharing the same generated class.
CSS Modules do not introduce a completely new styling language. Developers continue to write ordinary CSS, including selectors, media queries, pseudo-classes, custom properties, and other standard CSS features supported by their build environment.
The main difference is how class names are processed and applied.
3. How CSS Modules Work
CSS Modules depend on a build process. A development environment must understand how to process .module.css files.
A typical workflow contains several steps.
First, a developer creates a CSS Module file.
/* Profile.module.css */
.profile {
padding: 24px;
background: white;
}
.name {
font-size: 24px;
font-weight: 700;
}Next, the component imports the file.
import styles from "./Profile.module.css";
function Profile() {
return (
<section className={styles.profile}>
<h2 className={styles.name}>Developer Profile</h2>
</section>
);
}The build system processes the stylesheet and generates unique class names. It also creates a mapping that allows the JavaScript module to access the generated identifiers through properties such as styles.profile and styles.name.
When the application renders, the correct generated classes are assigned to the HTML elements.
This process provides a connection between the stylesheet and the component without requiring developers to manually generate unique class names.
The exact processing mechanism depends on the framework and bundler. Modern React frameworks often provide CSS Modules support directly, while other projects may require configuration through tools such as webpack or another compatible build system.
4. Creating Your First CSS Module
The easiest way to understand CSS Modules is to create a small component.
Start with a project structure:
src/
components/
Profile/
Profile.jsx
Profile.module.cssCreate the stylesheet:
/* Profile.module.css */
.profile {
max-width: 500px;
padding: 24px;
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 12px;
}
.heading {
margin-bottom: 12px;
color: #0f172a;
font-size: 24px;
}
.description {
color: #64748b;
line-height: 1.6;
}Create the React component:
import styles from "./Profile.module.css";
function Profile() {
return (
<article className={styles.profile}>
<h2 className={styles.heading}>
Frontend Developer
</h2>
<p className={styles.description}>
Building responsive and accessible web applications.
</p>
</article>
);
}
export default Profile;The imported styles object contains the generated class-name mappings.
The styles.profile expression refers to the local .profile class, while styles.heading refers to .heading.
This approach keeps the component and its styling closely connected. If another component uses a .profile class in its own CSS Module, the two classes can remain independent.
5. Why the .module.css Naming Convention Matters
Many React and Next.js environments recognize CSS Modules through the .module.css filename convention.
For example:
Button.module.css
Header.module.css
Dashboard.module.css
ProductCard.module.cssThe extension signals that the stylesheet should be processed as a CSS Module rather than as a traditional global stylesheet.
A regular CSS file may be imported differently depending on the framework. Global CSS is generally intended for application-wide styles, while CSS Modules are intended for locally scoped component styling.
A useful convention is to keep the module filename close to the component that uses it.
For example:
components/
Button/
Button.jsx
Button.module.css
Navigation/
Navigation.jsx
Navigation.module.css
ProductCard/
ProductCard.jsx
ProductCard.module.cssThis makes it easier to identify which styles belong to which component.
6. Understanding Local Class Names
In CSS Modules, local class names are exported through the imported mapping.
Consider:
/* Button.module.css */
.button {
padding: 12px 20px;
}
.primary {
background: #2563eb;
color: white;
}
.secondary {
background: #e2e8f0;
color: #0f172a;
}The component can use these classes individually or combine them.
import styles from "./Button.module.css";
function Button() {
return (
<div>
<button className={`${styles.button} ${styles.primary}`}>
Save
</button>
<button className={`${styles.button} ${styles.secondary}`}>
Cancel
</button>
</div>
);
}The shared .button class provides the base structure, while the other classes define visual variations.
This is a useful approach for component libraries because a single component can support multiple visual states without creating unrelated global styles.
Developers should remember that the original class names are accessed through the exported mapping. Writing className="button" would refer to a literal global class name, not automatically to the generated local class.
7. Combining Multiple CSS Module Classes
Real applications often need to combine several styling conditions.
For example, a button may have a base style, a size, and a visual variant.
/* Button.module.css */
.button {
border: none;
border-radius: 8px;
cursor: pointer;
font-weight: 600;
}
.small {
padding: 8px 12px;
font-size: 13px;
}
.large {
padding: 14px 24px;
font-size: 16px;
}
.primary {
background: #2563eb;
color: white;
}
.danger {
background: #dc2626;
color: white;
}A component can combine classes using template literals.
import styles from "./Button.module.css";
function Button() {
return (
<button className={`${styles.button} ${styles.large} ${styles.primary}`}>
Create Account
</button>
);
}For more complex conditions, a class-name utility can make the code easier to read.
For example, a project may use the clsx package.
import clsx from "clsx";
import styles from "./Button.module.css";
function Button({ variant = "primary", size = "medium" }) {
return (
<button
className={clsx(
styles.button,
styles[variant],
styles[size]
)}
>
Continue
</button>
);
}The clsx package is optional. Developers can implement the same logic using template literals or conditional expressions.
The important principle is to keep the component's visual states explicit and predictable.
8. Using CSS Modules with Conditional Styling
CSS Modules can work with component state and props.
Suppose an alert component has success, warning, and error states.
/* Alert.module.css */
.alert {
padding: 16px;
border-radius: 8px;
border: 1px solid transparent;
}
.success {
background: #f0fdf4;
border-color: #86efac;
color: #166534;
}
.warning {
background: #fffbeb;
border-color: #fcd34d;
color: #92400e;
}
.error {
background: #fef2f2;
border-color: #fca5a5;
color: #991b1b;
}The React component can select the correct class using a prop.
import styles from "./Alert.module.css";
function Alert({ type = "success", message }) {
const alertClass = styles[type] || styles.success;
return (
<div className={`${styles.alert} ${alertClass}`} role="status">
{message}
</div>
);
}
export default Alert;The component can now be reused with different states.
<Alert type="success" message="Your changes were saved." />
<Alert type="warning" message="Please review your information." />
<Alert type="error" message="The operation could not be completed." />For production code, the component should validate or constrain accepted variant names rather than assuming arbitrary input always corresponds to an exported class.
This pattern is useful for notifications, form validation messages, status labels, payment states, and dashboard indicators.
9. Understanding Global Styles in CSS Modules
CSS Modules scope local class names, but applications still need global styles.
Global styles commonly include:
Base typography
Document background
CSS resets
Shared font declarations
Global design tokens
Browser-wide accessibility defaults
For example, an application might use a global stylesheet:
/* globals.css */
* {
box-sizing: border-box;
}
html {
font-family: Arial, sans-serif;
}
body {
margin: 0;
background: #f8fafc;
color: #0f172a;
}
button,
input,
textarea,
select {
font: inherit;
}A component can then use its own CSS Module for local styling.
/* Header.module.css */
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px 28px;
background: white;
border-bottom: 1px solid #e2e8f0;
}The global stylesheet defines the application baseline, while the module defines the component-specific appearance.
CSS Modules also provide a :global() mechanism for explicitly writing selectors that should remain global.
For example:
:global(.third-party-widget) {
font-family: Arial, sans-serif;
}This can be useful when styling elements created by a third-party library or integrating with markup that cannot easily receive locally generated class names.
Global selectors should be used deliberately. If too many component rules are made global, the benefits of CSS Modules become weaker.
10. Using Global and Local Selectors Together
Sometimes a component needs to style a global element or class while keeping its own class names scoped.
CSS Modules support explicit global selector syntax.
.container {
padding: 20px;
}
.container :global(.external-widget) {
margin-top: 16px;
}Here, .container is locally scoped, while .external-widget is treated as a global class.
This is useful when a component contains markup produced by a third-party package.
For example, a date picker or charting library may generate internal HTML with class names that are not controlled by the application.
However, developers should avoid relying excessively on the internal class names of third-party packages. Those names may change between versions. Prefer documented customization APIs, theme properties, or supported class-name options when available.
11. Composing Styles with CSS Modules
CSS Modules support composition, allowing one local class to reuse declarations from another class.
For example:
/* Button.module.css */
.base {
padding: 12px 20px;
border-radius: 8px;
font-weight: 600;
cursor: pointer;
}
.primary {
composes: base;
background: #2563eb;
color: white;
}
.secondary {
composes: base;
background: #e2e8f0;
color: #0f172a;
}A component can import and use the composed class.
import styles from "./Button.module.css";
function Button() {
return (
<div>
<button className={styles.primary}>Submit</button>
<button className={styles.secondary}>Cancel</button>
</div>
);
}The generated class mapping for a composed class can include multiple class names.
Composition is useful for sharing declarations between related styles without duplicating every rule.
Some CSS Modules implementations also support composing from another module.
.button {
composes: base from "./Shared.module.css";
background: #2563eb;
}The exact support and processing behavior depend on the CSS Modules implementation used by the build tool.
Composition should be kept understandable. Deep chains of composed styles can make it difficult to determine where a declaration originates. For larger design systems, clear base classes and explicit variants are often easier to maintain.
12. Using CSS Custom Properties with CSS Modules
CSS Modules and CSS Custom Properties solve different problems and work well together.
CSS Modules provide local class-name scoping. CSS Custom Properties provide reusable values that can be inherited and changed at runtime.
For example:
/* Card.module.css */
.card {
padding: var(--card-padding, 20px);
background: var(--card-background, white);
color: var(--card-text, #0f172a);
border-radius: var(--card-radius, 12px);
}A React component can pass custom values through inline styles.
import styles from "./Card.module.css";
function Card({ background, children }) {
return (
<article
className={styles.card}
style={{
"--card-background": background
}}
>
{children}
</article>
);
}This combines the strengths of both techniques.
The component's class remains locally scoped, while the visual value can be customized dynamically.
This approach is especially useful for reusable components, themeable applications, white-label platforms, and design systems.
13. CSS Modules and Responsive Design
CSS Modules support ordinary media queries.
A component can keep its responsive behavior inside its own stylesheet.
/* ProductGrid.module.css */
.grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 24px;
}
@media (max-width: 900px) {
.grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 600px) {
.grid {
grid-template-columns: 1fr;
}
}The React component simply applies the local class.
import styles from "./ProductGrid.module.css";
function ProductGrid({ children }) {
return <div className={styles.grid}>{children}</div>;
}Keeping responsive rules inside the component stylesheet makes it easier to understand how that component behaves across different viewport sizes.
For larger projects, developers should also consider container queries. A component's layout may depend more on the width of its parent container than on the width of the entire browser window.
CSS Modules do not interfere with container queries.
/* ProductPanel.module.css */
.panel {
container-type: inline-size;
}
.content {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
}
@container (min-width: 600px) {
.content {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}This makes components more adaptable when reused in different parts of an application.
14. CSS Modules in React Applications
React's component architecture makes CSS Modules particularly useful.
A React application often contains components with independent responsibilities. Each component can have a matching CSS Module.
For example:
src/
components/
Header/
Header.jsx
Header.module.css
Sidebar/
Sidebar.jsx
Sidebar.module.css
ProductCard/
ProductCard.jsx
ProductCard.module.css
Footer/
Footer.jsx
Footer.module.cssThe Header component imports only its own stylesheet.
import styles from "./Header.module.css";
function Header() {
return (
<header className={styles.header}>
<h1 className={styles.logo}>Business Portal</h1>
<nav className={styles.navigation}>
<a href="/">Home</a>
<a href="/services">Services</a>
</nav>
</header>
);
}
export default Header;Its stylesheet can define local classes without needing application-wide prefixes.
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px 28px;
background: white;
}
.logo {
margin: 0;
color: #2563eb;
font-size: 22px;
}
.navigation {
display: flex;
gap: 20px;
}This approach improves component ownership. A developer working on the Header can usually locate its markup and styling without searching through a large global stylesheet.
15. CSS Modules in Next.js
Next.js supports CSS Modules as part of its standard styling options.
A common naming convention is:
Button.module.cssA component can import the module directly.
import styles from "./Button.module.css";
export default function Button() {
return (
<button className={styles.button}>
Get Started
</button>
);
}The stylesheet contains:
.button {
padding: 12px 20px;
background: #2563eb;
color: white;
border: none;
border-radius: 8px;
}In the Next.js App Router, CSS Modules can be imported into components within the application. They are useful for keeping component-specific styles close to their corresponding UI.
Global styles are typically imported through the application's root layout.
For example:
// app/layout.js
import "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}A page or component can separately import its CSS Module.
// app/dashboard/page.js
import styles from "./Dashboard.module.css";
export default function DashboardPage() {
return (
<main className={styles.dashboard}>
<h1 className={styles.title}>Dashboard</h1>
</main>
);
}This separates application-wide styling from locally scoped page and component styling.
Developers should follow the framework's current styling guidance, particularly when working with global stylesheet imports, server components, and shared layouts.
16. CSS Modules with TypeScript
TypeScript can improve the reliability of CSS Module usage by providing type information for imported class names.
In many modern frontend setups, the build system or framework provides CSS Module typing support. In other environments, developers may need to configure declarations.
A basic declaration file might look like this:
declare module "*.module.css" {
const classes: {
readonly [key: string]: string;
};
export default classes;
}This tells TypeScript that importing a CSS Module produces an object containing class-name strings.
A component can then import the stylesheet:
import styles from "./Profile.module.css";
type ProfileProps = {
name: string;
role: string;
};
export default function Profile({
name,
role
}: ProfileProps) {
return (
<article className={styles.profile}>
<h2 className={styles.name}>{name}</h2>
<p className={styles.role}>{role}</p>
</article>
);
}A generic declaration provides basic support, but it may not detect misspelled class names at compile time. Some projects use generated CSS Module types or framework-specific tooling to provide more precise checking.
For example, if a stylesheet exports profile but a component references styles.profle, a strongly typed setup can identify the mistake before runtime.
This becomes more valuable in large applications where CSS Modules contain many classes and are shared across multiple components.
17. CSS Modules and Component Libraries
Component libraries provide reusable interface elements that can be shared across multiple applications.
CSS Modules can help isolate the visual implementation of these components.
A button library might include:
ui/
Button/
Button.jsx
Button.module.css
Input/
Input.jsx
Input.module.css
Modal/
Modal.jsx
Modal.module.css
Alert/
Alert.jsx
Alert.module.cssEach component owns its local styles, reducing accidental conflicts with consuming applications.
However, component libraries often need customization options. A library should not assume that every consumer wants exactly the same colors, spacing, or typography.
CSS Custom Properties can provide a customization layer.
/* Button.module.css */
.button {
background: var(--ui-button-background, #2563eb);
color: var(--ui-button-text, white);
border-radius: var(--ui-button-radius, 8px);
padding: var(--ui-button-padding, 12px 20px);
}A consuming application can define the variables globally or within a specific container.
:root {
--ui-button-background: #0f766e;
--ui-button-radius: 999px;
}This allows a component library to maintain scoped class names while exposing a controlled customization interface.
18. CSS Modules Compared with Other Styling Approaches
CSS Modules are one of several approaches used in modern frontend development. Understanding their differences helps developers choose an appropriate solution.
Traditional Global CSS
Global CSS uses ordinary class names that can affect any matching element in the document.
It is simple and widely supported, but large applications may experience naming conflicts and difficult-to-maintain stylesheets.
Global CSS remains useful for resets, typography defaults, shared tokens, and broad application-level rules.
CSS Modules
CSS Modules provide local class-name scoping through a build process.
They preserve familiar CSS syntax and work well with component-based applications.
They are useful when teams want predictable component styling without adopting a completely different styling language.
CSS-in-JS
CSS-in-JS approaches define or generate styles through JavaScript or TypeScript.
Different libraries use different runtime and build-time strategies. Some provide dynamic styling, theme contexts, and component-level style generation.
CSS-in-JS can be useful for highly dynamic component systems, but the trade-offs vary by library, including runtime overhead, server rendering behavior, bundle size, and developer workflow.
Utility-First CSS
Utility-first frameworks provide predefined classes for common styling decisions.
For example, a component may use utility classes for padding, colors, typography, and layout rather than creating a dedicated stylesheet for every component.
This can improve consistency and reduce custom CSS, although complex components may contain many utility classes.
Sass and Other CSS Preprocessors
Sass adds features such as variables, mixins, functions, and modular stylesheet organization.
CSS Modules and Sass can also be combined in compatible build environments.
Sass focuses on stylesheet authoring capabilities, while CSS Modules focus on local class-name scoping.
These approaches are not necessarily competitors. A project may use Sass for authoring features, CSS Modules for scoping, and CSS Custom Properties for runtime theming.
19. Performance Considerations
CSS Modules do not automatically make an application faster. Their primary purpose is organizing and scoping styles.
However, a well-structured CSS Module architecture can contribute to more manageable frontend code.
Component-specific stylesheets make it easier to understand which styles belong to which components. This can help developers remove unused styles and maintain a more deliberate styling structure.
Build tools can process CSS Modules as part of the application's asset pipeline. Depending on the framework, styles may be extracted, bundled, optimized, or loaded through framework-specific mechanisms.
Developers should consider several performance factors.
First, avoid unnecessarily large stylesheets. A module should contain styles relevant to the component rather than becoming a collection of unrelated application rules.
Second, avoid excessive duplication. Shared design tokens and reusable component patterns can reduce repeated declarations.
Third, minimize expensive rendering effects when building complex interfaces. CSS Modules do not change how the browser calculates layout, paints elements, or composites layers.
Fourth, test production builds. Development behavior may differ from production optimization, stylesheet extraction, and class-name generation.
Finally, measure actual performance rather than assuming that a particular styling method is always faster.
20. Accessibility with CSS Modules
CSS Modules do not change the accessibility requirements of HTML and CSS.
A component can have perfectly scoped styles and still be inaccessible if it lacks semantic structure, keyboard support, visible focus indicators, or appropriate text contrast.
For example, a button should use a real button element rather than a clickable generic container.
import styles from "./Button.module.css";
function SaveButton() {
return (
<button className={styles.button} type="button">
Save Changes
</button>
);
}The stylesheet should preserve a visible focus indicator.
.button {
padding: 12px 20px;
border: none;
border-radius: 8px;
background: #2563eb;
color: white;
cursor: pointer;
}
.button:focus-visible {
outline: 3px solid #f59e0b;
outline-offset: 3px;
}For form controls, ensure that labels are correctly associated with inputs.
For status messages, use suitable semantic roles where appropriate. For interactive controls, make sure keyboard users can reach and operate them.
CSS Modules simply provide a way to organize the styling. Accessibility must be designed into the component itself.
21. Common CSS Modules Mistakes
Using Literal Class Names Instead of Imported Classes
A common mistake is importing a CSS Module but then writing a plain class string.
Incorrect:
import styles from "./Card.module.css";
function Card() {
return <div className="card">Content</div>;
}Correct:
import styles from "./Card.module.css";
function Card() {
return <div className={styles.card}>Content</div>;
}The second example uses the generated local class name.
Using Global Selectors Unnecessarily
CSS Modules provide local scoping, but developers can weaken that isolation by using broad global selectors.
For example, global element selectors that modify every heading or paragraph should generally belong in a deliberate global stylesheet, not inside an individual component module.
Forgetting the Module Filename
A stylesheet named Card.css may not be processed as a CSS Module in environments that rely on the .module.css convention.
Use the naming convention supported by the framework or bundler.
Creating Too Many Tiny Components
CSS Modules encourage component-level styling, but that does not mean every small visual element needs a separate component and stylesheet.
Component boundaries should reflect meaningful responsibilities and reuse opportunities.
Overusing Composition
Composition can reduce duplication, but deeply nested composition relationships may make styles difficult to trace.
Prefer a clear base class and a manageable set of variants.
Mixing Component Styles with Application-Wide Rules
A component stylesheet should generally focus on its own interface. Global resets, shared typography, and application-level defaults are better placed in global stylesheets.
Assuming CSS Modules Solve Every Styling Conflict
CSS Modules reduce local class-name collisions, but they do not eliminate every possible CSS conflict.
Global styles, inherited properties, CSS Custom Properties, element selectors, third-party stylesheets, and cascade layers can still influence the final result.
Understanding the CSS cascade remains important.
22. Best Practices for Professional CSS Modules Architecture
Start with a clear relationship between components and their stylesheets. A component and its CSS Module should normally be stored close together.
Use meaningful class names within each module. Since class names are locally scoped, there is less need for extremely long names, but names should still explain their purpose.
Separate global styling from component styling. Keep resets, global typography, shared design tokens, and broad application rules in dedicated global files.
Use CSS Custom Properties for shared design values. This provides a common visual foundation while CSS Modules keep component classes locally scoped.
Build reusable components around clear responsibilities. Avoid turning every small HTML element into an independent component unless there is a meaningful reason.
Use explicit variants for component states such as primary, secondary, disabled, success, and danger. Keep variant behavior predictable and document supported options.
Use responsive rules close to the components whose behavior they control. Consider container queries for components that must adapt to their available space.
Keep accessibility in the component implementation. Preserve focus visibility, semantic HTML, sufficient contrast, and appropriate interaction behavior.
Finally, test the application after significant styling changes. Check multiple pages, viewport sizes, themes, and interactive states. CSS Modules reduce naming conflicts, but visual regression testing and careful review remain valuable.
23. Practical Project: Build a Reusable Product Card System with CSS Modules
The following project demonstrates how CSS Modules can be used to create reusable product cards in a React application.
The goal is to build a card component that supports different products, visual variants, and responsive layouts.
Step 1: Create the Project Structure
src/
components/
ProductCard/
ProductCard.jsx
ProductCard.module.css
ProductGrid/
ProductGrid.jsx
ProductGrid.module.css
App.jsxStep 2: Create the Product Card Stylesheet
/* ProductCard.module.css */
.card {
display: flex;
flex-direction: column;
overflow: hidden;
padding: 20px;
background: white;
border: 1px solid #e2e8f0;
border-radius: 12px;
box-shadow: 0 4px 12px rgb(15 23 42 / 5%);
}
.image {
width: 100%;
aspect-ratio: 16 / 10;
object-fit: cover;
border-radius: 8px;
}
.title {
margin: 16px 0 8px;
color: #0f172a;
font-size: 20px;
}
.description {
color: #64748b;
line-height: 1.6;
}
.price {
margin-top: auto;
padding-top: 16px;
color: #2563eb;
font-size: 22px;
font-weight: 700;
}
.button {
margin-top: 16px;
padding: 12px;
border: none;
border-radius: 8px;
background: #2563eb;
color: white;
cursor: pointer;
}
.featured {
border-color: #2563eb;
box-shadow: 0 8px 24px rgb(37 99 235 / 12%);
}Step 3: Build the Product Card Component
import styles from "./ProductCard.module.css";
function ProductCard({
image,
title,
description,
price,
featured = false
}) {
return (
<article
className={`${styles.card} ${
featured ? styles.featured : ""
}`}
>
<img
className={styles.image}
src={image}
alt={title}
/>
<h2 className={styles.title}>{title}</h2>
<p className={styles.description}>
{description}
</p>
<p className={styles.price}>{price}</p>
<button className={styles.button} type="button">
View Product
</button>
</article>
);
}
export default ProductCard;The component receives its content through props. Its styling remains inside its own CSS Module.
Step 4: Create a Responsive Product Grid
/* ProductGrid.module.css */
.grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 24px;
}
@media (max-width: 900px) {
.grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 600px) {
.grid {
grid-template-columns: 1fr;
}
}Create the grid component:
import styles from "./ProductGrid.module.css";
function ProductGrid({ children }) {
return (
<section className={styles.grid}>
{children}
</section>
);
}
export default ProductGrid;Step 5: Use the Components in the Application
import ProductCard from "./components/ProductCard/ProductCard";
import ProductGrid from "./components/ProductGrid/ProductGrid";
function App() {
return (
<main>
<h1>Featured Products</h1>
<ProductGrid>
<ProductCard
image="/images/laptop.jpg"
title="Professional Laptop"
description="A powerful laptop for business and development."
price="₹75,000"
featured
/>
<ProductCard
image="/images/monitor.jpg"
title="Ultra-Wide Monitor"
description="A large display for productive workflows."
price="₹28,000"
/>
<ProductCard
image="/images/keyboard.jpg"
title="Mechanical Keyboard"
description="A comfortable keyboard for everyday work."
price="₹5,000"
/>
</ProductGrid>
</main>
);
}
export default App;This example demonstrates how the application can reuse a single ProductCard component without creating separate global class names for each product.
The ProductCard stylesheet controls the visual structure, while ProductGrid controls the layout. Each module has a clear responsibility.
The same pattern can be extended to include product ratings, discount labels, stock indicators, category badges, and configurable themes.
Conclusion
CSS Modules provide a practical solution to one of the most common challenges in frontend development: managing styles in increasingly large applications. By locally scoping class names, they reduce accidental naming conflicts and make component-specific styling easier to organize.
Their greatest advantage is that developers can continue using familiar CSS while gaining a clearer relationship between components and their stylesheets. They work particularly well with React, Next.js, and other component-based frontend architectures.
CSS Modules are not a replacement for every CSS technique. Global styles remain useful for application-wide defaults, CSS Custom Properties provide runtime design tokens, and preprocessors can offer additional stylesheet authoring features. These techniques can work together within a well-planned frontend architecture.
For professional development, focus on clear component boundaries, meaningful local class names, controlled global styling, reusable variants, responsive behavior, accessibility, and consistent design tokens.
As your application grows, this structure makes it easier to maintain existing components, introduce new features, collaborate with other developers, and reduce unintended styling changes.
Learning CSS Modules is therefore an important step toward building organized, scalable, and maintainable frontend applications.
#CSSModules #ScopedCSS #ReactDevelopment #FrontendDevelopment #WebDevelopment