We often think of our pages as these full and complete documents full of elements and content. However, browsers are designed to handle documents like a stream. They begin to receive the document from the server and can render the document before it has completely downloaded. Each node is evaluated and rendered to the viewport as it is received.
Take a look at the body of an example document:
<body>
<div id="content">
<div class="module intro">
<p>Lorem Ipsum</p>
</div>
<div class="module">
<p>Lorem Ipsum</p>
<p>Lorem Ipsum</p>
<p>Lorem Ipsum <span>Test</span></p>
</div>
</div>
</body>
The browser starts at the top and sees a body
element. At this point,
it thinks it's empty. It hasn't evaluated anything else. The browser
will determine what the computed styles are and apply them to the
element. What is the font, the color, the line height? After it
figures this out, it paints it to the screen.
Next, it sees a div
element with an ID of content
. Again, at this
point, it thinks it's empty. It hasn't evaluated anything else. The
browser figures out the styles and then the div
gets painted. The
browser will determine if it needs to repaint the body—did the element
get wider or taller? (I suspect there are other considerations but
width and height changes are the most common effects child elements
have on their parents.)
This process continues on until it reaches the end of the document.
![](https://istack.dev59.com/pc7vG.webp)
CSS gets evaluated from right to left.
To determine whether a CSS rule applies to a particular element, it
starts from the right of the rule and works it's way left.
If you have a rule like body div#content p { color: #003366; }
then
for every element—as it gets rendered to the page—it'll first ask if
it's a paragraph element. If it is, it'll work its way up the DOM and
ask if it's a div
with an ID of content. If it finds what it's looking
for, it'll continue its way up the DOM until it reaches the body
.
By working right to left, the browser can determine whether a rule
applies to this particular element that it is trying to paint to the
viewport much faster. To determine which rule is more or less
performant, you need to figure out how many nodes need to be evaluated
to determine whether a style can be applied to an element.
那么为什么样式表的内容没有逐步应用(先是绿色,然后是红色)呢?
我认为答案是外部样式表在下载时会被解析,但只有整个样式表被解析后才会被应用。在解析样式表时,浏览器会优化不必要和冗余的CSS规则。我现在没有证据来支持这一点,但这个解释听起来对我来说是合理的,并且与您所看到的情况相符,无论是外部还是内联样式。