Nested CSS Rules

November 22, 2013
I love LESS. I love almost everything about it because it makes my code clean and readable. The only thing that I don't like is that I have to compile it to CSS. It would be so cool if most popular concepts from LESS would make its way into the native browser support. Just like jQuery has inspired browser vendors to add document.querySelector and document.querySelectorAll, I believe LESS will also influence browser.
But what feature is the more important? For me it is a no-brainer. I think nested rules is the single most important feature in LESS (or SASS). However, when I asked my colleges, I got various answers. Some said, it's got to be variables, others could not decide. So, I have created a little poll of what is the most coveted feature of LESS.

The Poll

Nested CSS Rules

Here are my reasons why I think nested CSS rules is the most important feature to be implemented in standard CSS. Below are two examples of a common HTML and CSS as we use it today:
And how it is implemented in LESS:

1. Nested Rules Make CSS readable

Over past 10 years, I have learned one thing about CSS: "It is easy to write CSS and hard to read". Due to its structure and cascading nature, if you change a padding in one rule, it might cause a butterfly effect throughout the page. Sometimes, it become virtually impossible to do a pixel perfect design and you would have to rewrite CSS rules from scratch. An ability to nest CSS rules makes it readable and easier to follow.

2. It directly corresponds to the nested HTML structure

Parent-child relationship is huge in HTML. Every DOM node is somebody's child. Because of absence of nested rules CSS's expressive power is very week.

3. Nested Rules fight proliferation of classes

Instead of adding one class for the structural block, many developers add classes into every single DOM element they need to style because it makes their CSS less complicated. Very soon the clean HTML code from previous example becomes cluttered: It is a bad practice to create a class for each element you want to style. The chances of name collision is higher and it looks flat. However, if CSS would allow nested rules, we would not have to add so many classes.

4. Nested Rules have proven themselves in LESS and SASS

It is one of the first things advertised by LESS and SASS: "You can nest CSS rules" and it catches the developer's eye. Nested rules are like Object Oriented Programming (OOP) in CSS.

5. Nested Rules contribute to a greater World Peace

Nested rules make developers happy. Happy developers fight less. Less fighting in the world increases World Peace.

User Comments

Other Articles