CSS specificity
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:
p{color:red;} .first{color:green;} <p class="first">三年级时,我还是一个<span>胆小如鼠</span>的小女孩。</p>
Both p and .first match the p tag, so which 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;} /*权值为1*/p span{color:green;} /*权值为1+1=2*/.warning{color:white;} /*权值为10*/p span.warning{color:purple;} /*权值为1+1+10=12*/#footer .note p{color:yellow;} /*权值为100+10+1=111*/
Note: There is also a special weight value--Inheritance also has a weight value but it is very low. The literature proposes that it is only 0.1, so it can be understood as the inherited weight is the lowest.
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>特殊性</title> <style type="text/css"> p{color:red;} .first{color:green;}/*因为权值高显示为绿色*/ span{color:pink;}/*设置为粉色*/ p span{color:purple;} </style> </head> <body> <h1>勇气</h1> <p class="first">三年级时,我还是一个<span>胆小如鼠</span>的小女孩,上课从来不敢回答老师提出的问题,生怕回答错了老师会批评我。就一直没有这个勇气来回答老师提出的问题。学校举办的活动我也没勇气参加。</p> <p id="second">到了三年级下学期时,我们班上了一节公开课,老师提出了一个很简单的问题,班里很多同学都举手了,甚至成绩比我差很多的,也举手了,还说着:"我来,我来。"我环顾了四周,就我没有举手。</p> </body> </html>