目录
出现组合的情况时候:组合的选择器和其他选择器相比,选择器的优先级顺序也是适用的
当同一个对象被多个选择器选中并修饰,产生冲突时,哪个选择器的优先级更高就需要考虑了。
可以发现,范围越小,定位越精确的,其优先级越高。
(ps:第二个行内样式,因为css的应用,在实际中用的不多,除非某些个别情况会少量使用)
示例程序:
<!DOCTYPE html>
<html>
<head>
<title>内部样式表演示</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="div1" id="div2">
</div>
</body>
</html>
div{
width: 200px;
height: 200px;
background-color: red;
}
效果:
……………………………………………………
若index.css改成:下面,标签选择器和类选择器产生了冲突
div{
width: 200px;
height: 200px;
background-color: red;
}
.div1{
background-color: blue; /*标签选择器的优先级,低于 类选择器*/
}
效果:发现,证实了标签选择器的优先级低于类选择器
……………………………………………………
若index.css改成:下面,标签选择器、类选择器、id选择器三个产生了冲突
div{
width: 200px;
height: 200px;
background-color: red;
}
.div1{
background-color: blue; /*标签选择器的优先级,低于 类选择器*/
}
#div2{
background-color: yellow; /*类选择器的优先级,低于 id选择器*/
}
效果:证实了,id选择器的优先级比类选择器和标签选择器都高
!important:强制优先。
这个通常不使用,可能会干扰程序的运行,除非特殊的情况下才会使用。
div{
width: 200px;
height: 200px;
background-color: red;
}
.div1{
/*但这儿使用强制优先*/
background-color: blue!important; /*标签选择器的优先级,低于 类选择器*/
}
#div2{
background-color: yellow; /*类选择器的优先级,低于 id选择器*/
}
效果:虽然,类选择器的优先级没有id选择器优先级高,但类选择器使用了强制优先。
当同一个标签的class有多个值的时候,产生冲突时的效果:
div的class有两个值,class="div1,div3",
<!DOCTYPE html>
<html>
<head>
<title>内部样式表演示</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="div1 div3" id="div2">
</div>
</body>
</html>
index.css:下面对div的class中的两个都设置了,此时就冲突了,
div{
width: 200px;
height: 200px;
background-color: red;
}
.div1{
background-color: blue;
}
.di3{
background-color: yellow;
}
效果:发现,当类选择器冲突时,以后出现的为准。。。。。(层层覆盖?)
出现组合的情况时候:组合的选择器和其他选择器相比,选择器的优先级顺序也是适用的
好吧,这个例子更加说明,这些选择器可以有千万种组合,你要时间够,就去试吧……………………XD
<!DOCTYPE html>
<html>
<head>
<title>内部样式表演示</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="d1" id="d2">
<div class="div1" id="div2"></div>
</div>
</body>
</html>
index.css
div{
width: 200px;
height: 200px;
background-color: red;
}
.d1 .div1{ /*空格选择器*/
background-color: yellow;
}
效果:发现,这也是ok的。当某些属性设置产生冲突时,优先级高的选择器组合而成的组合选择器,也还是比低级选择器优先级高。同时可以发现,其只有其在颜色设置上产生了冲突。div的大小设置还是起了作用(因为没有一个比div这个标签选择器更高的选择器也设置了大小)