Do not bloat less / sass nested rules, do not kill reusability

Wherever possible, we should avoid nested rules in less/sass.

When you start using less/sass and the way you can create nested rules to compile to full css, it is so Cool, but I found my team creating nested and overqualified rules automatically. We were happy about it, thinking all the css for a section will be in one place. If we change anything for abut page, it will not screw the contact page. So Good. But soon we realized that what we are creating, is a chunk of highly qualified css, which is not reusable anywhere else 🙁 . The probability of making such mistakes is higher when writing less/sass, you get trapped in semantics. Take a look at the code below:

.about-page {
    background: @grey;
    .page-title {
        font-size: 24px;
    }
}
.contact-page {
    background: @lighter-grey;
}

Now what about page-title for contact page ?? If you apply class .page-title on contact page heading, it will not work, because the css generated above is .about-page .page-title {...}. Now to make that work you will add .page-title to .contact-page as well. You are still happy as you think you are keeping all code formatted section wise, but you are doing some serious code duplication at the same time:

.about-page {
    background: @grey;
    .page-title {
        font-size: 24px;
    }
}
.contact-page {
    background: @lighter-grey;
    .page-title {
        font-size: 24px;
    }
}

Also when you increase specificity, you increase bloating. First of all you already have duplicate styles which are overqualified. And then to override these overqualified rules, you will make more rules which are much more qualified. You will end up in something like .contact-page .page-title.step-2 {...}. More lines of code which are completely unnecessary and can be easily avoided. You are sinking deeper and deeper mate.

Solution

  • Avoid nesting
  • Make all rules Global, as many as possible
  • Make rules Independent of sections and containers
  • Increase specificity of a rule if and when there is no other solution i.e. avoid over-qualification of rules
  • Keep looking at you generated css time to time. You need to set minify: false and recompile, do not commit that 😛

So, take a look at the final code below. This will save your life in near future . . .

.about-page {
    background: @grey;
}
.page-title {
    font-size: 24px;
}
.contact-page {
    background: @lighter-grey;
}

No Bloating, No Duplication, No Specificity loops, Easy Overriding, Use the page-title on as many pages as you want, and lesser lines of code. You did it !!

Will be adding Further reads in comments . . .

 

 

 

One Response to “Do not bloat less / sass nested rules, do not kill reusability”

Leave a Reply

  • (will not be published)