Open In App

SASS Nesting

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

SASS Nesting makes it easier and more efficient to write CSS by allowing you to nest your selectors inside one another, mimicking the structure of your HTML.

This removes the need to repeatedly write out parent selectors, improving readability and maintainability of your styles. SASS will compile the nested styles into standard CSS by automatically combining the selectors.

Basic Nesting in SASS

When writing nested selectors, you can structure your SASS code similarly to the HTML hierarchy. This allows for cleaner and more intuitive styling, especially for complex components or layouts.

Example 1: Basic Nesting

Let's look at a basic example of SASS nesting where we style an unordered list with nested list items and links.

SASS file:

ul {
list-style-type: none;

li {
display: inline-block;

a {
text-decoration: none;
display: inline-block;
padding: 10px 15px;
color: blue;
}
}
}

Compiled CSS file:

ul {
list-style-type: none;
}

ul li {
display: inline-block;
}

ul li a {
text-decoration: none;
display: inline-block;
padding: 10px 15px;
color: blue;
}

Nesting with Combinators

SASS also allows nesting with combinators like the adjacent sibling (+), child (>), and general sibling (~) combinators. These can be nested inside selectors for more complex relationships between elements.

Example 2: Nesting with Combinators

Here, we demonstrate how to use different combinators inside SASS nesting.

SASS file:

ul { 
+ li {
display: inline-block;
}
}

li {
> {
a {
text-decoration: none;
}
}
}

p ~ {
span {
text-decoration-line: underline;
text-decoration-style: double;
}
}

Compiled CSS file:


ul + li {
display: inline-block;
}

li > a {
text-decoration: none;
}

p ~ span {
text-decoration-line: underline;
text-decoration-style: double;
}

Similar Reads