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.
Basic selector nesting in SASS
& { nested-selector { property: value; } }The & symbol represents the parent selector.
You can nest selectors inside each other to reflect HTML structure.
title inside an element with class card..card { .title { color: blue; } }
ul inside a nav element.nav {
ul {
list-style: none;
}
}button..button { &:hover { background-color: green; } }
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.
<!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>
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.
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.