伪类

CSS的伪类以冒号:作为前缀,被添加到一个选择器的末尾,用于样式在特定情况下才被呈现到指定的元素时才被添加

:nth-child()

:nth-child(an+b):这个伪类找到所有当前元素的兄弟元素,按照位置顺序排序1…n,选择的结果为第(an+b)个元素。

a:nth-child(0n+2)匹配第二个a标签。

a:nth-child(2n+1)匹配1,3,5,7…2n+1位置上的标签,奇数标签,可以用a:nth-child(odd)代替。

a:nth-child(2n)匹配偶数位置上的标签,可以用a:nth-child(even)代替。

:last-child

这个伪类表示最后一个元素,比如下面的10个<div class="sb">test</div>

1
2
3
4
5
6
7
8
9
10
11
12
<div class="test"></div>
<div>dsadsa</div>
<div>dsadsa</div>
<div>dsadsa</div>
<div>dsadsa</div>
<div>dsadsa</div>
</div>
<style>
test > div:last-child {
background: #eee;
}
</style>

那么最后一个div的背景色变为#eee。

:last-of-type

选择这个伪类的子元素列表中最后一个给定类型的子元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div class="test">
<div>dsadsa</div>
<p>test~</p>
<div>dsadsa</div>
<div>dsadsa</div>
<div>dsadsa</div>
<p>test~</p>
<div>dsadsa</div>
</div>
<style>
test > p:last-of-type {
background: #eee;
}
</style>

在test下面的所有子元素中最后一个p的背景色变为#eee

:active、:link、:hover、:visited

这个伪类匹配被用户激活的元素,当用鼠标交互时,它代表用户按下键和松开键之间的时间。通常用来匹配tab键交互。通常用于button和a标签。

这个样式会被后声明的其他链接相关样式(link、hover、visited)覆盖,为了实现正常效果使用LVHA顺序定义相关样式::link:visited:hover:active

:checked

表示处于选中状态下checkbox、radio、option元素。

比如下面的例子:

1
2
3
4
:checked {
margin-left: 10px;
color: red;
}

:default

选择相关元素中默认的表单元素。

:focus

这个伪类表示获得焦点的元素。当用户点击或者使用触摸屏触摸时触发。主要用在input元素上,当用户点击输入框时修改input的样式。