Site icon Ampersand Tutorials

Nesting in SASS

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

Exit mobile version