With so many years of CSS, now only understand the real CSS matching principle, do not know if you are the same as me? Look at 1 simple css:
Div#divbox p span.red{color:red, according to our understanding of this CSS, the browser first looks for the DIV element with ID Divbox, and when found, finds all the p elements below it, and then finds all span elements, When a span is found to be red, the style is applied. How simple and understandable the principle, but this understanding is completely opposite, wrong.
Matching principle:
Browser CSS matching is not lookup from left to right, but from right to left. For example Div#divbox p span.red{color:red, the browser's lookup order is as follows:
First look for all class= ' red ' span elements in HTML, find out if there are p elements in their parents ' elements, and then determine if there is a DIV element with ID divbox in the parent element of P, if all exist then match.
The benefit of browsers looking from right to left is to filter out extraneous style rules and elements as early as possible. such as HTML and CSS:
The following are the referenced contents:
<style>
Div#divbox P span.red{color:red
<style>
<body>
<div id= "Divbox" >
<p><span>s1</span></p>
<p><span>s2</span></p>
<p><span>s3</span></p>
<p><span class= ' Red ' >s4</span></p>
</div>
</body>
If you search from left to right, you will find many unrelated p and span elements first. If you search from left to right, you first find the elements of the <span class= ' Red ' >. Firefox called this search method for key selector (keyword query), the so-called keyword is the final (rightmost) rules of style rules, the above key is span.red.
Simple, efficient CSS:
The so-called efficient CSS is to let the browser find the style matching elements of the time as far as possible to search, listed below some of our common writing CSS to make some inefficient errors (also I used to make mistakes, but also the old thought that writing is efficient):
1, do not use the logo signature before the ID selector
General wording: Div#divbox
Better writing: #divBox
Explanation: Because the ID selector is unique, adding a Div adds an unnecessary match.
2. Do not use the label signature before the class selector
General wording: span.red
Better writing:. Red
Explanation: Same as the first, but if you define more than one. Red, and under different elements is the style is not the same, you can not remove, such as your CSS file is defined as follows:
p.red{color:red;
Span.red{color: #ff00ff}
If this definition is not removed, it will be confused after the removal, but it is advisable not to write
3. Use of hierarchical relationships as little as possible
General wording: #divBox P. red{color:red;}
Better writing:. red{.}
4. Use class instead of hierarchical relationship
General wording: #divBox ul Li A{display:block;
Better writing:. Block{display:block;}