
Quick answer: Nesting in SASS lets you place CSS selectors inside other selectors, so a child rule sits under its parent instead of repeating the whole path. This mirrors your HTML structure, shortens your stylesheet, and keeps related rules together. Nesting also supports the parent selector, which makes hover states and combined classes easy to write.
Learn Nesting in SASS with easy guide and working examples
Nesting in SASS / SCSS is easy with the help of “&” to achieve the nesting. In SASS “&” behaves uniquely and it denotes the current selector. The selector changes as we nest down. If we want to define a division with a width of 80% and aligning to a centre with margin style, we use the following code.
.main{
width:80%;
margin: 0 auto;
}Now if we want to apply the class inside main and with the name of main_new. The class main_new defines the style inside the main class. We can nest it with the following code.
.main{
width:80%;
margin:0 auto;
&_new{
font-size: 2em;
}
}The above SCSS will compile into the following CSS code.
.main {
width:80%;
margin:0 auto;
}
.main_new{
font-size: 2em;
}To copy the SCSS expression string to the subclass, we can use “#{&}” to copy the entire main class expression to the following subclass. If we want to achieve the CSS as mentioned below, we can use the nesting with interpolation.
Desired CSS
.main{
width:80%;
margin:0 auto;
}
.main .main_new{
font-size:2em;
}Actual SCSS Code
.main{
width:80%;
margin:0 auto;
#{&}_new{
font-size: 2em;
}
}Successfully, you have learned nesting in SASS. In the next tutorial, we will be learning Partials in SASS, how to implement partials in your website project
Frequently asked questions
What is nesting in SASS and why use it?
It lets you place a selector inside another selector, so you write less repeated code and your CSS matches your HTML structure.
How do I style a hover state with nesting?
Write the parent selector, then a colon and hover inside it, like nav { a { &:hover { color: teal; } } }.
Does nesting create extra CSS weight?
No. SASS flattens the nested rules when compiling, so the output is the same as hand written CSS.
