一:样式冲突
通过不同的选择器选中同一个元素,进行一样的样式设定,发生样式冲突时,应用哪一个样式由选择器的权重(优先级)决定
二:选择器的权重
内联样式 1000
id选择器 100
类和伪类选择器 10
元素选择器 1
通配符、子选择器、相邻选择器等。如*、>、+ 0000
继承的样式 没有优先级
!important 最高优先级 慎用
注意:
1,比较优先级时,需要将所有选择器的优先级进行相加计算,最后优先级越高,则优先显示
2,(并集选择器)分组选择器是单独计算的
3,如果优先级计算后相同,此时则优先使用靠下的样式
4,选择器的累加,不会超过上一级数量级,例如:类选择器再高也不会超过id选择器 量变达不到质变
总结:一般来说:选择器越具体,优先级越高
以下是代码示例:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><style>div,#box1 {color: pink;}/* .red {background-color: yellow !important;} *//* 设置了字体大小,span会继承,但如果通配选择器设置了,就听通配选择器的 */#box1 {color: blue;font-size: 30px;}/* 标签选择器+id选择器 *//* div#box1 {color: red;font-size: 30px;} *//* 单独计算 *//* div,span {color: slateblue;} *//* 没有优先级,谁都能改 *//* * {font-size: 50px;} */span{color: royalblue !important;}</style></head><body><!-- class="red" --><div id="box1" class="red" >我是div元素<span class="s1 red" style="color: salmon">我是div中的span元素</span><em class="e1" >我是div中的em元素</em></div></body>
</html>