DEV Community

Nesting in SASS

Sarah Chima on November 10, 2017

Remember nesting in HTML? The thing we do all the time when we put a <p> in a <div> and a <span> in the <p> like this? ...
Collapse
 
satansdeer profile image
Maksim Ivanov • Edited

Great tutorial, I like that you've also made a caution about the excessive nesting.

In my work I avoid styling elements by #id's. Usually I use them only as anchors.

Also a quick note about naming. For example you've used .sidebar-list-link.

I prefer to avoid this kind of "nesting" in naming as well and use only one level of nesting. So I would do .sidebar and .sidebar-list. And .list maybe with .for-sidebar modifier with .list-link. Basically I would follow a bit modified version of BEM methodology.

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks for the addition. 😊😊

Collapse
 
lynnewritescode profile image
Lynne Finnigan • Edited

Great article! Another use for the ampersand that people might find useful would be to reference parent selectors with the ampersand at the end.

h1 {
    .parent-selector & {
        *insert styles*
    }
}

Very powerful!

Collapse
 
sarah_chima profile image
Sarah Chima

Awesome!!! Thanks for sharing this Lynne.

Collapse
 
aurelkurtula profile image
aurel kurtula • Edited

Great tutorial. A fantastic tip on this:

   .sidebar {
       position: fixed;
       height: 100%;

       &-list {
           background-color: white;

           &-link {
               text-decoration: none;
            }
        }
    }

Never thought about doing that.

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you😊

Collapse
 
rhymes profile image
rhymes

Well explained.

Just an addition: I've been using stylelint and stylelint-config-sass-guidelines to keep my SASS files in check and you can also configure it to set a maximum nesting depth.

Collapse
 
sarah_chima profile image
Sarah Chima

That's awesome. I'll look at them. Thanks for sharing.

Collapse
 
jehdiaizon profile image
Jehdi Aizon

what does the & do when it is before or after a nested class or id??

Collapse
 
bethberry profile image
BethBerry

Nesting with SASS does not seem to work for me? banishing negativity spells

Collapse
 
isabelsinclair profile image
IsabelSinclair

Should you nest everything in SASS? comment rendre un homme amoureux