2

I'm trying to understand exactly how and in what order CSS is processed by the browser. I already know CSS is read from right to left, but more specifically, I want to know if:

  1. The browser goes through each element in the DOM, and for each element, scans through the CSS rules to find which style matches?...or if:
  2. The browser goes through each CSS rule and for each selector, scans through the DOM to find a DOM element that matches that selector?

(Or perhaps this even varies between browsers?)

4
  • If you look at a page with any DOM inspection tool, you'll see that every element gets properties assigned to it. I think that's how they do it. I don't think the browser maintains a table of selectors and which elements are assigned to which selector. Commented Jan 11, 2013 at 18:00
  • this article may help you to understand a little more. Commented Jan 11, 2013 at 18:01
  • So what's the question? What are you going to use this knowledge for? Commented Jan 11, 2013 at 18:01
  • 1
    This is an important question. Knowing how a browser processes CSS will allow you write it efficiently Commented Jul 17, 2016 at 20:44

2 Answers 2

4

As far as I know, this is not defined by the CSS standard, which only specifies results, not means to reach them. Since both "algorithms" would give you the same visual output, they should both be valid implementations, assuming they also take into account the dynamic nature of webpages (that is, elements may move, be added, modified or deleted nearly any time by Javascript and this may change the CSS rules they match, or even that other elements match).

This should be implementation-dependent. Different browsers don't have to all do it the same way. Rest assured, though, that competition in the browser space is fierce enough that you shouldn't have to worry about the performance implications of setting a CSS rule.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for "competition in the browser space is fierce enough that you shouldn't have to worry about the performance implications of setting a CSS rule"
0

One thing to note about CSS processing heirarchy is when linking to CSS files.

A stylesheet called with link will load sooner:

<link rel='stylesheet' type='text/css' href='foo.css'> 

than a stylesheet called with @import:

<style> @import url('foo.css'); </style> 

This is a very simplistic example, but you get the point. You can read much more here: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.