CSS optimization, nested selectors and indexing of identifier / class names in the browser

When rendering web pages and applying styles, index index identifiers and class names for efficient searches, or traverse the entire DOM from the top each time an identifier or class name is specified to achieve the correct element.

I am interested for optimization reasons and whether it is worth giving browser hints (longer selectors) where the object of a certain identifier is located. I.e.

#container #one-of-many-container-siblings #my-id 

instead:

 #my-id 

Will the previous ones give better performance if the DOM is large enough?

+6
source share
4 answers

In fact, it works in the opposite way, what you think.

Remember that browsers analyze the CSS selector from right to left.

It:

 #container #one-of-many-container-siblings #my-id 

more steps will be taken than this:

 #my-id 

See: http://www.css-101.org/descendant-selector/go_fetch_yourself.php

Given the question you just asked, I recommend you read this article:

http://css-tricks.com/efficiently-rendering-css/

This will help you write a more efficient selector:

 #main-navigation { } /* ID (Fastest) */ body.home #page-wrap { } /* ID */ .main-navigation { } /* Class */ ul li a.current { } /* Class * ul { } /* Tag */ ul li a { } /* Tag */ * { } /* Universal (Slowest) */ #content [title='home'] /* Universal */ 
+8
source

An identifier definition in HTML / CSS is one instance of an element. Assuming you follow this rule, all you need is an identifier for this element. The browser will search and detect this item and stop.

With your β€œhint”, he will first start searching for the first element, then the second, then the third, to a halt. This, as you can see, is more inefficient.

When working with classes, this can become a bit more ambiguous and fuzzy, but the general rule is that the fewer selectors, the better. If you find yourself doing three, four, or five selectors, you should consider a little refactoring, such as adding classes or identifiers in strategic places, or even not so specific to your CSS selectors.

+2
source

Using a shorter version will always be faster because fewer checks are performed, however I don’t know why CSS will need to be optimized on the page on this page.

+1
source

It is best to use 2 or less selectors, usually for better performance.

+1
source

Source: https://habr.com/ru/post/889223/


All Articles