1.css选择器
1.1 基础选择器
基础选择器包括三种:html标签选择器,class选择器和id选择器三种。
html标签选择器的使用:直接写出HTML标签名,例如:
p {color: red;}
代表将文档中所有的p元素内部的文字渲染成红色。
class选择器:”.”加class名,例如:
.class {color: blue;}
id选择器:”#”加id名,例如:
#id {color: #333;}
1.2 综合选择器
综合选择器,顾名思义就是将基础选择器进行各种组合。
有以下几种:
后代选择器:el1 el2
:将el1元素中后代是el2的所有元素设置样式。
子代选择器:el1>el2
: 将el1子代中的el2元素设置样式。
交集选择器:el1el2
: 选中el1与el2的交集。注意:HTML标签一定只能写在前面如p#text
。
并集选择器: el1,el2
:选中el1与el2的并集。
序列选择器: el1 el2:first-child
或者el1 el2:last-child
:选中el1中el2的第一个或者最后一个元素。css3中nth-of-child可以取代。
相邻兄弟选择器:el1+el2
: 选中与el1相邻的el2元素。
普通兄弟选择器: el1~el2
: 选中与el1相邻的一系列el2元素。
2.css选择器冲突解决规则
如下面代码所示。
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
</head>
<style>
/*本例以#lvl4的p元素为目标元素。*/
/*选中同一元素时,进行权重比较*/
.level1 .level2 #lvl4 {
color:red;
}
.level4#lvl4 {
color: violet;
}
/*权重相同以最后一个为准*/
.level1 #lvl2 p {
font-size: 30px;
}
.level3 p#lvl4 {
font-size: 50px;
}
#lvl1 .level3 p {
font-size: 20px;
}
/*若一选择器选中目标元素的上级,而另一个选中目标本身,则以后者为先。*/
#lvl1>#lvl2>#lvl3 {
font-weight: bold;
}
#lvl4 {
font-weight: normal;
}
/*若目标未被选中,则套用离目标最近的上级元素的样式*/
.level1 .level2 {
background-color: #000;
}
.level3 {
background-color: #999;
}
/*如果某一属性设置了!important则无视其优先级直接套用*/
</style>
<body>
<div class="level1" id="lvl1">
<div class="level2" id="lvl2">
<div class="level3" id="lvl3">
<p class="level4" id="lvl4">
Lorem ipsum dolor sit amet.
</p>
</div>
</div>
</div>
</body>
</html>