SASS
Trending

Nesting in SASS

Learn Nesting and Interpolation 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

Dinesh Kumar R

Director at Mahadhi Technologies, Mahadhi Healthcare, Ampersand Academy, Motorjob, Swadata Analytics. I create engaging user interfaces for enterprise-level applications using HTML, CSS, SCSS, JavaScript, JQuery, TypeScript, Angular Material, Bootstrap, MaterializeCSS. I also craft beautiful, lead-generating websites which engages the visitors. Connect with me with your creative needs. Favourite Quote: If everything seems under control, you are just not going fast enough.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button