Nested selectors performance impact and LESS

css, css-selectors, less, optimization, performance

Solution

That is correct. Browsers evaluate selectors from right to left. It will try to find a `span` inside a `li.pinfo-box` and so on.

One rule of thumb to folllow when writing LESS is: do not nest more than 3-4 levels.

This will prevent your selectors from growing to big, while you will still be able to benefit from the nesting feature in LESS.

A good example of "useless" nesting is when styling lists. Sometimes I write the selectors like this:

`#wrapper .blog-post ul`, `#wrapper .blog-post ul li`

Is it really necessary to specify that the `li` must be inside a `ul`? It will probably be enough writing:

`#wrapper .blog-post li`

All of this is good to know. BUT: This is not the first thing to dive into when trying to optimize your sites performance. Spend some time lower the number of request or something else instead.

Problem

I have been reading for the past 1.5 hours about this and still couldn't find a concise and decisive answer. As far as I understood browsers parse CSS selectors from right to left. That means a long CSS selector such as this: ``` .card .container .businesscard .pinfo li.pinfo-box span:first-child ``` is one of the least efficient lines of code to ever appear here in SO. First of all, am I right on this one? Secondly, I am designing a rich UI using LESS, which ultimately produces this kind of mammoth selectors out of the nested designs I am coding. What can be done to avoid this kind of selectors? Rely on classes and IDs alone? But then again what is the purpose of using LESS if you can't write nested CSS? Your input is appreciated.

Original source

Related problems