CSS optimisation, nested selectors, and browser indexing of ID's/class names
When rendering web pages and applying styles, do browsers index ID's and class names for efficient search, or does it traverse the entire DOM from the top each time开发者_运维问答 an ID or class name is specified to reach the correct element.
I'm wondering for optimisation reasons, and whether it's worth giving the browser hints (longer selectors) to where an object of a certain ID is. I.e.
#container #one-of-many-container-siblings #my-id
instead of:
#my-id
Will the former yield better performance if the DOM is quite large?
It actually works the opposite way to what you're thinking.
Remember that browsers parse CSS selectors right to left.
This:
#container #one-of-many-container-siblings #my-id
will take more steps to match than this:
#my-id
See: http://www.css-101.org/descendant-selector/go_fetch_yourself.php
Considering the question you've just asked, I recommend you read this article:
http://css-tricks.com/efficiently-rendering-css/
It will help you write more efficient selectors:
#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 */
The definition of an ID in HTML/CSS is a single instance of an element. Assuming you're following that rule, then all you need is the ID of that element. The browser will search through and find that element and stop.
With your "hinting" one, it will first search for the first item, then the second, then the third, before stopping. This, as you can probably see, is more inefficient.
When dealing with classes, this can get a little more ambiguous and fuzzy, but the general rule is the fewer the selectors, the better. If you find yourself doing three or four or five selectors, it might be worth considering a little refactoring, such as adding classes or IDs in strategic places, or even not being so specific with your CSS selectors.
Using the shorter version will always be faster because there a fewer checks being performed, however I don't know why on would need to optimize the CSS on a page.
its best to use 2 or less selectors as a rule of thumb for performance.
精彩评论