CSS 复合选择器
交集选择器
交集选择器由两个选择器构成,其中第一个为标签选择器,第二个为class选择器,两个选择器之间不能有空格。
<style type="text/css">
div {
width: 100px;
height: 30px;
background-color: red;
}
div.one {
background-color: blue;
}
</style>
<div class="one"></div>
<div class="two"></div>

并集选择器
并集选择器是和的意思,用逗号隔开的,所有选择器都会执行后面样式。
<style type="text/css">
.one, span {
display: block;
width: 100px;
height: 50px;
background-color: red;
font-size: 30px;
}
</style>
<span class="one">文字1</span>
<span>文字2</span>

后代选择器
后代选择器又称为包含选择器,用来选择元素或元素组的后代,把外层标签写在前面,内层标签写在后面,中间用空格分隔,内层标签就成为外层标签的后代。
<style type="text/css">
div {
width: 100px;
height: 100px;
background-color: blue;
}
.father div {
width: 50px;
height: 50px;
background-color: red;
}
</style>
<div class="father">
<div></div>
</div>

子元素选择器
子元素选择器只能选择作为某元素子元素的元素。其写法就是把父级标签写在前面,子级标签写在后面,中间跟一个 > 进行连接,注意,符号左右两侧各保留一个空格。
<style type="text/css">
div {
width: 100px;
height: 100px;
background-color: blue;
}
.father > div {
width: 50px;
height: 50px;
background-color: yellow;
}
</style>
<div class="father">
<div></div>
</div>

伪类选择器
伪类选择器用于向某些选择器添加特殊的效果。比如给链接添加特殊效果, 比如可以选择 第1个,第n个元素
链接伪类选择器
:link 未访问的链接
:visited 已访问的链接
:hover 鼠标移动到链接上
:active 选定的链接
注意:写的时候,他们的顺序尽量不要颠倒 ,按照 lvha 的顺序。
<style type="text/css">
a {
font-size: 30px;
color: gray;
}
a:hover {
color: red;
}
</style>
<a>这是一个a链接</a>

位置伪类选择器
:first-child:选取属于其父元素的首个子元素的指定选择器
:last-child:选取属于其父元素的最后一个子元素的指定选择器
:nth-child(n):匹配属于其父元素的第 N 个子元素,不论元素的类型
:nth-last-child(n):选择器匹配属于其元素的第 N 个子元素的每个元素,不论元素的类型,从最后一个子元素开始计数。
n 可以是数字、关键词或公式
<style>
ul {
list-style: none;
}
li:first-child {
color: pink;
}
li:last-child {
color: purple;
}
li:nth-child(4) {
color: skyblue;
}
</style>
<ul>
<li>第一个</li>
<li>第二个</li>
<li>第三个</li>
<li>第四个</li>
<li>第五个</li>
</ul>

属性选择器
选取标签带有某些特殊属性的选择器,我们称为属性选择器
<style>
div[class^=content] {
color: pink;
}
div[class$=footer] {
color: blue;
}
div[class*=test] {
color: red;
}
</style>
<div class="header">header</div>
<div class="nav">nav</div>
<div class="aaatestbbb">aaatestbbb</div>
<div class="content">content</div>
<div class="content2">content2</div>
<div class="footer">footer</div>

伪元素选择器
分伪类和伪元素区别:
- 伪类本质上是为了弥补常规CSS选择器的不足,以便获取到更多信息
- 伪元素本质上是创建了一个有内容的虚拟容器
- 可以同时使用多个伪类,但伪元素在一个选择器中只能出现一次,并且只能出现在末尾
- 伪元素默认行内元素
<style>
p::first-letter {
font-size: 20px;
color: red;
}
p::first-line {
color: blue;
}
p::selection {
color: orange;
}
p::before {
content: "开始";
}
p::after {
content: "结尾";
}
</style>
<p>我们在学H5 <br> 哈哈哈哈哈哈哈</p>

|