Why do CSS selectors match from right to left

Under CSS rules (such as  . box span), an index tree that conforms to the rules will be formed. The nodes from top to bottom of the tree are the nodes that match the selectors in the rules from right to left.

 

Matching rules from left to right

The general thinking is that the more detailed the selector is specified, the easier it is to match and the better the performance. This view is based on the fact that each CSS style is queried to match the nodes in the dom. The higher the level of detail of the selector, the less redundant the query and the better the performance. For example:

// 布局
<div class="box">
    <div class="div1">
		<span class="span1">测试1</span>
	</div>
    <div class="div2">
		<span class="span2">测试2</span>
	</div>
</div>


.box .span1{} // 样式1
.box .div1 .span1{} // 样式2

According to the above rules, style 1 will do one more comparison than style 2, that is, the comparison of span2. This way of CSS query matching dom nodes is the so-called left-to-right matching rule (for CSS selectors) - for style 1, it matches 5 times from left to right and 7 times from right to left .

Matching rules from right to left

Another way of thinking is that the simpler the selector specification, the easier it is to match and the better the performance. The basis of this view is to query and match the style in CSS for each dom node, the higher the level of detail of the selector, the more times the query matches and the worse the performance. For example:

// 布局
<div class="box">
    <div class="div1">
		<span class="span">测试1</span>
	</div>
</div>


.div1 .span{} // 样式1
.box .div1 .span{} // 样式2

According to the above rules, for the pattern matching of "Test 1", pattern 1 needs one less match than pattern 2. This way of dom node query matching CSS selectors is the so-called right-to-left matching rule (for CSS selectors) - for style 1, match 3 times from left to right, and match from right to left 2 times.

It is clear that the performance of the two matching rules is very different. It is because right-to-left matching filters out a large number of unqualified rightmost nodes (leaf nodes) in the first step; while the performance of left-to-right matching rules is wasted on failed searches.

Summarize

More selectors in CSS will not match, so when considering performance issues, what needs to be considered is how to improve efficiency when the selectors do not match, and the redundancy in the selector combination should be minimized as much as possible. Right-to-left matching is for this purpose, and this strategy can make CSS selectors more efficient when they don't match.

Guess you like

Origin blog.csdn.net/qq_34402069/article/details/129627493