Every Element Has a Value for Every Property Whether You Wrote One or Not, and the Browser Will Not Place a Single Box Until It Knows Them All
Last timeFrom Bytes to a Tree
How competing rules are reduced to one value per property for every element, where inherited and default values come from, and why nothing can be positioned until this finishes.
Finding the rules that apply
The tree from the previous lesson says what the elements are and how they nest.
It says nothing about what any of them look like. Supplying that is a separate
pass, and it runs per element and per property.
Start with one element. Every selector in every stylesheet is tested against
it to find the declarations that are candidates. That is the first thing worth
pricing, because the work is the number of rules multiplied by the number of
elements, and a large page has a few thousand of each.
Matching runs right to left, which is the opposite of how selectors read. Given
a selector naming a container and then an item inside it, the browser checks
whether this element is such an item first, and only then walks up its
ancestors looking for the container. Starting from the left would mean
searching downwards through an unknown number of descendants, which is far
worse.
Sorting the candidates
Several declarations now compete for the same property. The resolution is
mechanical and has exactly three stages, applied in order, with no judgement
anywhere.
Origin comes first. A declaration marked important by the page author beats one
from the user beats one from the browser default, and declarations not marked
important run in the opposite direction, with author beating user beating
default.
Specificity comes second, and only if origin tied. Count the identifiers in the
selector, then the classes and attribute tests, then the element names. Compare
those three counts in that order, and the first difference decides.
- a value that orders selectors the same way the real comparison does, for small counts
- number of identifier selectors
- number of class and attribute selectors
- number of element name selectors
Document order comes third and breaks every remaining tie. The declaration that
appears later in the sheet, or in a sheet that was linked later, wins.
The lesson stops here
3 more paragraphs to go
You have read the opening. The rest of the argument, the problems that check whether it landed, and the lines worth keeping at the end all come with a plan.
The first lesson of every course in the library reads the whole way through, free, so you can see exactly what the rest of them are.
See the planThe contentsThis is the reading half
Starting the course gives you your own copy of it. Every idea on every page has problems standing under it, marked with a reason rather than a tick, and any sentence you do not believe can be opened and argued with. None of that can happen on a page nobody owns.
The contents