How does browser read CSS selector?

One of the important things to understand about how browsers read your CSS selectors, is that they read them from right to left. That means that in the selector ul > li a[title=”home”] the first thing thing interpreted is a[title=”home”]. This first part is also referred to as the “key selector” in that ultimately, it is the element being selected.

#main-nav > li {   }  /* Slower than it might seem */

Even though that feels weirdly counter-intuitive… Since ID’s are so efficient we would think the browser could just find that ID quickly and then find the li children quickly. But in reality, the relatively slow li tag selector is run first.

If the browser can determine the element you are looking for using just one selector and you’ve used more, you have inefficient code on your hands.

So you have to be very careful on how you are choosing your selector. Give unique IDs to fetch the single element Or give class name properly to identify group of elements based on your requirement. I

You should aim never to use more than two selectors to identify a rule. While going overboard by creating useless selectors in your markup is also inefficient, it’s still better to add additional IDs and classes in your markup than to require extensive drilling in your CSS to find the right element.

There are four main types of selectors in CSS–ID, class, tag and universal.

•IDs are unique elements denoted by the hash, like our old friend #current.

•Classes are reusable elements denoted by a period, for example: .comment.

•Tags denote HTML elements such as lists, links and so on, for example ul, li and a.

•Universal refers to tags that target every element on the page, such as *.

But why do browsers match CSS selectors from right to left?.

If you start by just matching the rightmost part of the selector against your element, then chances are it won’t match and you’re done. If it does match, you have to do more work, but only proportional to your tree depth, which is not that big in most cases.

On the other hand, if you start by matching the leftmost part of the selector… what do you match it against? You have to start walking the DOM, looking for nodes that might match it. Just discovering that there’s nothing matching that leftmost part might take a while.So browsers match from the right; it gives an obvious starting point and lets you get rid of most of the candidate selectors very quickly.

Tagged:

One thought on “How does browser read CSS selector?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: