前端 - dom是如何与css规则匹配的?
黄舟
黄舟 2017-04-17 11:05:31
0
3
540

比如我有如下CSS代码:

.red {
  background-color: red;
}
table {
  background-color: yellow;
}
<table>
  <tr>
    <td>123</td>
    <td>123</td>
  </tr>
  <tr>
    <td>123</td>
    <td class="red">123</td>
  </tr>
</table>

解析CSS的时候先找到class="red",把那个td设置成红色,然后找到table,把table设置成黄色,同时他又能分辨出class="red"那个td,并且不会覆盖它,这是怎么做到的?是不是每个规则都会去看之前解析的规则是否匹配了。
比如有n个dom,m个规则,每个dom都要去从这m个规则中找是否匹配,这个匹配的算法是什么样的呢?会把所有的css规则生成一棵树然后每个dom在树上查找,还是会用其他查找算法呢?这篇文章讲了一些,求高人解惑:http://calendar.perfplanet.com/2011/css-selector-performance-has-changed-for-the-better/

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
洪涛

Actually, it’s not as complicated as you said. It’s just a matter of priority and inheritance

Inheritance: If a style that can be used for inheritance is set on the parent element, but the same style is not defined on the child element, it will be directly inherited from the parent element, such as font-size, background, etc.; some styles It cannot be inherited, such as border, padding, etc.;

Priority: If multiple selectors are set for the same element in the style sheet to operate it, then in the case of the same priority, the last one set will overwrite all the previous settings, and the element itself sets Style priority will also be higher than inherited styles;

Tell me about the rules of priority:

  • idThe selected priority is 0 1 0 0
  • classThe selected priority is 0 0 1 0
  • ele The selected priority is 0 0 0 1
  • Inherited styles have no priority

Here I just mentioned three common priorities. For more priority rules, LZ can check out css权威指南(第二版);

Back to your question, if table sets the background color, the sub-element td will inherit it directly. However, a td is set for a certain class="red", according to the above priority Level rules, other td have no priority, they just inherit the style of table, and the priority of this class="red of td is 0010, has the highest priority, so apply it;

One last thing to add: Even if the sum of priorities is greater than 10, it will not move forward, just like: 0 0 1 0 is greater than 0 0 0 15

左手右手慢动作

The easiest way is to find an open source code and take a look, such as webkit.

1. HTML

  • Browser exploration - webkit part - analysis (1) HTML origin
  • Browser exploration - webkit part - parsing HTML (2) decoding and HTMLTokenizer processing
  • Browser exploration - webkit part - parsing HTML (3) HTMLToken processing

2. CSS

  • Webkit core exploration [2] - Webkit CSS implementation

The blogs I recommended above are all series. If you are interested, you can read other articles by the way.

Hope it helps.

Ty80

The w3c standard will only tell you what algorithm to use to achieve this and leave it to the browser, such as the v8 engine

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template