Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 208
Michael Waterfall Avatar asked May 27 '11 17:05

Michael Waterfall


People also ask

How do you optimize CSS selectors?

To optimize the CSSOM construction, remove unnecessary styles, minify, compress and cache it, and split CSS not required at page load into additional files to reduce CSS render blocking.

What are nested selectors in CSS?

What is CSS nesting? This syntax has been possible with CSS preprocessors like Sass and Less. As you can see from both code samples above, nesting is enclosing a selector inside another selector. Nesting helps you to group related styles and write CSS in a nested hierarchy.

What is ID nesting in CSS?

Nesting in CSS CSS Nesting is used to call nested element, means child selector or descendant selector from parent. There are two selectors in nesting, child selector and descendant selector.


1 Answers

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 */
like image 116
thirtydot Avatar answered Nov 11 '22 15:11

thirtydot