Sometimes we set different CSS style codes for the same element, so which CSS style will be enabled for the element? Let’s take a look at the following code
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>特殊性</title> <style type="text/css"> p{color:red;} .first{ color:green; /*因为权值高显示为绿色*/ } span{ color:pink; /*设置为粉色*/ } </style> </head> <body> <h1>勇气</h1> <p class="first">三年级时,我还是一个<span>胆小如鼠</span>的小孩, 上课从来不敢回答老师提出的问题,生怕回答错了老师会批评我。就一直没有这个勇气来回答老师提出的问题。学校举办的活动我也没勇气参加。</p> <p id="second">到了三年级下学期时,我们班上了一节公开课,老师提出了一个很简单的问题,班里很多同学都举手了,甚至成绩比我差很多的, 也举手了,还说着:"我来,我来。"我环顾了四周,就我没有举手。</p> </body> </html>
Both p and .first match On the p label, what color will be displayed? green is the correct color, so why? This is because the browser determines which CSS style to use based on the weight, and the CSS style with the higher weight is used.
The following are the weight rules:
The weight of the label is 1, the weight of the class selector is 10, and the maximum weight of the ID selector is 100. For example, the following code
p{color:red;} /*The weight is 1*/
p span{color:green;} /*The weight is 1+1=2* /
.warning{color:white;} /*The weight is 10*/
p span.warning{color:purple;} /*The weight is 1+1+10= 12*/
#footer .note p{color:yellow;} /*The weight is 100+10+1=111*/
Note: There is another weight It's quite special - inheritance also has a weight but it's very low. Some literature suggests that it's only 0.1, so it can be understood that inheritance has the lowest weight
Next Section