Blog>
Snippets

Optimizing CSS Output with Sass Nesting in Next.js

Showcase how to use Sass's nesting feature in a Next.js component to create more readable and maintainable styles, and explain how to avoid excessive nesting that can lead to overly specific selectors.
// Install Sass for your Next.js project
npm install sass
This command is used to install the Sass preprocessor in a Next.js project, allowing you to use Sass features such as variables, mixins, and nesting within your stylesheets.
import React from 'react';
import './Button.module.scss';

export default function Button({ children }) {
  return (
    <button className="button">
      {children}
    </button>
  );
}
In this React functional component, we're importing a Sass stylesheet for a button component. This will allow us to style the button element using Sass's features.
// Button.module.scss
.button {
  padding: 10px 20px;
  border: none;
  background-color: #007bff;
  color: white;
  font-size: 16px;

  // Nested pseudo-class
  &:hover {
    background-color: #0056b3;
  }

  // Nested element
  .icon {
    margin-right: 5px;
  }

  // Avoiding excessive nesting
  // BAD: & .text .label { ... }
  // GOOD:
  .text {
    font-weight: bold;

    // Nested with a direct descendant
    > .label {
      color: #ff0;
    }
  }
}
In the Sass stylesheet, we use nesting to target elements within the scope of the `.button` class, such as `&:hover` for hover state and `.icon` for a child icon element. We avoid excessive nesting by not creating overly specific selectors, like `& .text .label`, but instead, use `.text` with direct child selectors.