0
0
SASSmarkup~5 mins

Basic selector nesting in SASS

Choose your learning style9 modes available
Introduction

Nesting selectors helps you write CSS in a cleaner and more organized way. It groups related styles together, making your code easier to read and maintain.

When styling elements inside a container or component, like buttons inside a card.
When you want to apply styles to child elements only within a specific parent.
When you want to avoid repeating the parent selector multiple times.
When you want to visually group related CSS rules for better clarity.
When you want to write less code but keep it structured.
Syntax
SASS
& { nested-selector { property: value; } }

The & symbol represents the parent selector.

You can nest selectors inside each other to reflect HTML structure.

Examples
This styles any element with class title inside an element with class card.
SASS
.card {
  .title {
    color: blue;
  }
}
This removes bullet points from ul inside a nav element.
SASS
nav {
  ul {
    list-style: none;
  }
}
This changes the background color when hovering over an element with class button.
SASS
.button {
  &:hover {
    background-color: green;
  }
}
Sample Program

This example shows a card with a title and description. The styles use nested selectors in SASS to group styles for .title and .description inside .card. The card also changes background color on hover. The tabindex="0" makes the card focusable by keyboard for accessibility.

SASS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Basic Selector Nesting Example</title>
  <style>
    /* Compiled CSS from SASS nesting example */
    .card {
      border: 2px solid #333;
      padding: 1rem;
      max-width: 300px;
      font-family: Arial, sans-serif;
    }
    .card .title {
      color: #2a7ae2;
      font-weight: bold;
      font-size: 1.25rem;
      margin-bottom: 0.5rem;
    }
    .card .description {
      color: #555;
      font-size: 1rem;
    }
    .card:hover {
      background-color: #f0f8ff;
    }
  </style>
</head>
<body>
  <section class="card" tabindex="0" aria-label="Information card">
    <h2 class="title">Welcome to Nesting</h2>
    <p class="description">This card uses nested selectors in SASS for styling.</p>
  </section>
</body>
</html>
OutputSuccess
Important Notes

Remember that nesting too deeply can make your CSS hard to read and maintain.

Use the & symbol to refer to the parent selector when needed, like for pseudo-classes.

Always test your compiled CSS in the browser to see the visual effect.

Summary

Nesting groups related CSS selectors inside a parent for cleaner code.

The & symbol represents the parent selector in nested rules.

Use nesting to reflect the HTML structure and avoid repeating selectors.