tezvyn:

Sass Nesting: Write CSS That Mirrors Your HTML

AI-drafted, machine-checkedSource: sass-lang.combeginner

Sass nesting lets you structure your styles like your HTML, avoiding repetitive selectors. Use it for components with clear parent-child relationships, like a navbar's list items. The footgun is over-nesting, which creates bloated, overly-specific CSS.

WHY IT EXISTS Plain CSS can be very repetitive. When styling a component like a navigation bar, you often find yourself writing nav ul, nav li, and nav a, repeating the nav selector each time. This makes the code verbose and decouples the visual hierarchy of the styles from the structure of the HTML.

THE MENTAL MODEL Think of Sass nesting as organizing your CSS rules into the same tree structure as your HTML. If a <ul> is inside a <nav> in your HTML, you can put the ul style rule inside the nav style rule in your Sass file. The Sass preprocessor then automatically generates the correct, flat CSS selectors for you.

HOW IT WORKS When you write a style rule inside another, Sass combines the outer rule's selector with the inner rule's. An inner rule for li placed inside an outer rule for nav will be compiled into the CSS selector nav li. Sass handles this combination automatically, creating descendant selectors by default. It's also smart enough to handle selector lists (like .alert, .warning) and combinators (like > for a direct child or + for an adjacent sibling).

WHEN TO USE IT Use nesting for styling self-contained components where the styles are tightly coupled to the component's structure. It's perfect for navigation menus, cards, articles, or any element where you have distinct child elements that only need styling within that parent's context. A common rule of thumb is to limit nesting to three or four levels deep to maintain readability and avoid specificity issues.

WHEN NOT TO USE IT Avoid deep nesting. Each level of nesting increases selector specificity, making styles harder to override later. A selector like .sidebar .module .content .header h2 is extremely specific and brittle. Deep nesting also bloats the final CSS file, increasing download and parse times for the browser. If a style is reusable and not tied to a specific parent, define it as a top-level class instead of nesting it.

ONE CANONICAL EXAMPLE To style a navigation menu, your Sass could be written like this:

nav { ul { margin: 0; padding: 0; list-style: none; }

li { display: inline-block; }

a { display: block; padding: 6px 12px; text-decoration: none; } }

Sass compiles this into the following standard CSS:

nav ul { margin: 0; padding: 0; list-style: none; }

nav li { display: inline-block; }

nav a { display: block; padding: 6px 12px; text-decoration: none; }

Read the original → sass-lang.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.