0
0
SASSmarkup~5 mins

Property nesting for related styles in SASS

Choose your learning style9 modes available
Introduction

Nesting selectors helps keep related styles together. It makes your code cleaner and easier to read.

When you want to style a button and its hover state together.
When you have a menu with items and sub-items that share styles.
When you want to group styles for a form and its input fields.
When you want to organize styles for a card component and its title and content.
When you want to reduce repetition in your CSS code.
Syntax
SASS
$selector {
  property: value;
  nested-selector {
    property: value;
  }
}
Use indentation to show nesting clearly.
Nested selectors are written inside the parent selector's block.
Examples
This styles a button and changes its color when hovered.
SASS
.button {
  color: blue;
  &:hover {
    color: red;
  }
}
Styles a menu and its items together.
SASS
.menu {
  background: white;
  .item {
    padding: 1rem;
  }
}
Groups styles for a card and its parts.
SASS
.card {
  border: 1px solid #ccc;
  .title {
    font-weight: bold;
  }
  .content {
    margin-top: 0.5rem;
  }
}
Sample Program

This example shows a card with nested styles for its title, content, and hover background color. Nesting keeps related styles inside the .card block.

SASS
@use 'sass:color';

.card {
  border: 2px solid #333;
  padding: 1rem;
  background: color.scale(#eee, $lightness: -10%);

  .title {
    font-size: 1.5rem;
    font-weight: bold;
    color: #222;
  }

  .content {
    margin-top: 0.5rem;
    color: #555;
  }

  &:hover {
    background: color.scale(#eee, $lightness: 10%);
  }
}
OutputSuccess
Important Notes

Always indent nested styles properly to avoid confusion.

Use & to refer to the parent selector inside nested blocks.

Nesting helps reduce repeated selectors and keeps styles organized.

Summary

Nesting groups related styles inside one block.

Use & to refer to the parent selector for states like :hover.

It makes your styles easier to read and maintain.