in the previous article on how to use the document structure and CSS selector for elements to apply a variety of rich styles, today to have a good chat about CSS cascade and inheritance, first talk about concepts.
Inheritance: The mechanism by which an element passes property values to its descendant elements, the popular point is that certain attributes of an element can be passed to child elements by inheritance.
Such as:
<p><span> Test Inheritance </span> This is not the content in span </p>
P{color:red}, you will see that the P element and the text in the trial element become red, because the properties of the P element are inherited by span. However, there are attributes that cannot be passed through inheritance.
such as border will not be obtained through inheritance. In fact, inheritance is very good understanding, but to match the Cascade to understand together.
Cascade: When determining what style an element should use, it is necessary to consider the particularity of inheritance and declaration, so which CSS style to enable, this process is called cascading.
The above mentioned the particularity, then we will focus on the look.
First throw a question, below 2 pairs of rules, which one will win?
H1{color:red}
Body H1{color:blue}
H2{color:red}
H2.color{color:green}
of the above 2 pairs of rules, obviously only one wins, but which should win? The answer lies in the specificity of each selector.
The specific particularity of a selector is as follows:
1. For each id attribute value given in the rule, the particularity plus 0,1,0,0
2. For each class in the rule, select the matching attribute selector and pseudo-class, the particularity plus 0,0,1,0
3. For each element and pseudo-element in the rule, the particularity 0,0,0,1
4. The binding and wildcard characters have no contribution to the particularity.
5. The particularity of the inline style plus 1,0,0,0
6. Inherited attributes are not specific, even 0 are not specific, so lower than the wildcard character.
7.!important always wins.
So for the two sets of rules above, there is the result:
h1{color:red} 0,0,0,1
Body H1{color:blue} 0,0,0,2
h2{color:red} 0,0,0,1
H2.color{color:green} 0,0,1,0
So red and green will come into effect.
So, the rules for cascading are as follows:
1. Find all the selectors in your code.
2. Rule display weights sort and origin sort, mark! Important's style is top priority and has three origins: Creator, Reader, user agent.
3. The specificity of the element declaration is sorted.
4. The order in which the element declarations appear is ordered.
Read more about CSS inheritance and cascading articles please follow topic.alibabacloud.com!