tezvyn:

CSS Nesting: Grouping Related Styles

AI-drafted, machine-checkedSource: developer.mozilla.orgbeginner
CSS Nesting: Grouping Related Styles

CSS nesting groups related styles like folders for files. Instead of repeating parent selectors, you write child rules inside the parent. This is great for component-based styling, but over-nesting creates specificity headaches that are hard to override.

WHY IT EXISTS: Before native nesting, styling complex components meant repeating parent selectors over and over (e.g., .card .title, .card .button). This was verbose, error-prone, and made stylesheets hard to read. CSS Nesting was created to provide the organizational benefits of preprocessors like Sass directly in the browser.

THE MENTAL MODEL: Think of CSS nesting as creating a visual hierarchy in your stylesheet that mirrors your HTML structure. A .card rule can contain the styles for its .title and .button children directly inside its curly braces. This co-locates related styles, making it easier to find, understand, and maintain the styling for a complete component in one place.

HOW IT WORKS: You write a style rule for a parent element. Inside its declaration block ({ ... }), you can then write new style rules for its descendants. The browser automatically combines the parent selector with the nested child selector. For example, a td rule nested inside a table rule is interpreted by the browser as table td. To refer to the parent selector itself, such as for adding a pseudo-class, you use the ampersand (&) symbol, as in &:hover.

WHEN TO USE IT: Nesting is ideal for self-contained components like cards, modals, or navigation bars where styles are tightly coupled to the HTML structure. It dramatically improves readability and maintainability for these modules. It's also perfect for applying state-based styles with pseudo-classes (&:hover, &:focus) or modifier classes (&.is-active).

WHEN NOT TO USE IT: Avoid nesting too deeply. A good rule of thumb is to go no more than three levels deep. Each level of nesting increases selector specificity, which can make your CSS difficult to override later, leading to "specificity wars" and the temptation to use !important. Only nest rules that are truly contextually dependent on the parent.

ONE CANONICAL EXAMPLE: Without nesting, styling a card's title and hover state requires separate rules: .card { ... }, .card h2 { ... }, and .card:hover { ... }. With nesting, you can write this more concisely: .card { background: white; border-radius: 8px; h2 { font-size: 1.5rem; } &:hover { box-shadow: 0 4px 8px rgba(0,0,0,0.1); } } . Notice how the h2 is directly inside .card, and & is used for the :hover state.

Read the original → developer.mozilla.org

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.