Blog>
Snippets

Using CSS Modules in Next.js 14 for Component-Level Styles

Demonstrate how to create and use CSS Modules to apply styles scoped to a particular component, ensuring that the layout styling does not leak to other parts of the application.
import styles from './Button.module.css';

export default function Button() {
  return <button className={styles.error}>Error Button</button>;
}
This is the content of 'Button.js'. It demonstrates how to import a CSS Module and use it in a Next.js component. The styles from 'Button.module.css' are applied to the button element ensuring they are scoped to just this button component.
.error {
  background-color: red;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  font-weight: bold;
  cursor: pointer;
  margin: 5px;
}

.error:hover {
  opacity: 0.8;
}
This is the content of 'Button.module.css'. It defines styles specifically for the '.error' class used within 'Button.js'. Using CSS Modules ensures these styles are scoped and do not affect any other elements outside the component.