CSS3 新增伪类详解
warning:
这篇文章距离上次修改已过473天,其中的内容可能已经有所变动。
CSS3 中新增了很多伪类选择器,以下是一些常用的伪类选择器及其解释和示例代码:
:first-child:选择父元素的第一个子元素。
p:first-child {
color: red;
}:last-child:选择父元素的最后一个子元素。
p:last-child {
color: red;
}:nth-child(n):选择父元素的第 n 个子元素。
p:nth-child(2) {
color: red;
}:nth-last-child(n):选择父元素的倒数第 n 个子元素。
p:nth-last-child(2) {
color: red;
}:only-child:选择没有兄弟元素的元素。
p:only-child {
color: red;
}:empty:选择没有子元素(包括文本)的元素。
p:empty {
display: none;
}:target:选择当前活动的锚点元素。
#section1:target {
background-color: yellow;
}:enabled和:disabled:选择可用或不可用的表单元素。
input:enabled {
border-color: blue;
}
input:disabled {
border-color: grey;
}:checked:选择被选中的表单元素(如复选框或单选按钮)。
input:checked {
background-color: green;
}:not(selector):选择不符合制定选择器的元素。
p:not(.exclude) {
color: blue;
}:nth-of-type(n)和:nth-last-of-type(n):与:nth-child(n)和:nth-last-child(n)类似,但是基于元素类型进行计数。
p:nth-of-type(2) {
color: red;
}:only-of-type:选择仅有一个同类型兄弟的元素。
p:only-of-type {
color: red;
}:in-range和:out-of-range:选择其值在指定范围内和范围外的input元素。
input:in-range {
border-color: green;
}
input:out-of-range {
border-color: red;
}:invalid和:valid:选择无效或有效的form元素。
input:invalid {
border-color: red;
}
input:valid {
border-color: green;
}:read-only和:read-write:选择只读或可读写的input元素。
input:read-only {
background-color: lightgrey;
}:root:选择文档的根元素。
:root {
background-color: white;
}:lange(language):选择具有指定语言的元素。
p:lang(it) {
font-style: italic;
}:dir(direction):选择指定文本方向的元素。
p:dir(rtl) {
text-align: right;
}:scope:选择当前作用域的元素。
td:scope {
评论已关闭