在CSS中,伪类选择器用于选择处于特定状态或符合特定条件的元素。以下是一些常用的伪类选择器,它们可以用来选择特定模式的元素:
:hover:选择鼠标指针浮动在上面的元素。
a:hover { color: red;
}
:active:选择并激活的元素,通常用于链接或按钮被点击时。
button:active { background-color: gray;
}
:focus:选择获得焦点的元素,例如用户正在输入的输入框。
input:focus { border: 1px solid blue;
}
:visited:选择用户已经访问过的链接。
a:visited { color: purple;
}
:first-child:选择其父元素的第一个子元素。
p:first-child { font-weight: bold;
}
:last-child:选择其父元素的最后一个子元素。
p:last-child { color: green;
}
:nth-child(n):选择其父元素的第n个子元素。n可以是数字、关键字(如even或odd),或者是一个公式(如2n或2n+1)。
li:nth-child(2n) { background-color: gray;
}
:nth-last-child(n):与:nth-child(n)相反,从最后一个子元素开始计数。
li:nth-last-child(2) { color: orange;
}
:first-of-type:选择其父元素中同类型元素的第一个。
p:first-of-type { font-size: 18px;
}
:last-of-type:选择其父元素中同类型元素的最后一个。
p:last-of-type { text-decoration: underline;
}
:nth-of-type(n):选择其父元素中同类型元素的第n个。
li:nth-of-type(3) { list-style-type: none;
}
:nth-last-of-type(n):与:nth-of-type(n)相反,从同类型元素的最后一个开始计数。
li:nth-last-of-type(1) { text-transform: uppercase;
}
:not(selector):选择不匹配指定选择器的元素。
div:not(.class-name) { background-color: lightblue;
}
:empty:选择没有子元素的元素(包括文本节点)。
div:empty { display: none;
}
:lang(language):选择指定语言的元素。
p:lang(fr) { font-style: italic;
}