css3伪类选择器

admin 20 0

**CSS3伪类选择器详解**

在CSS3中,伪类选择器是一种用于选择HTML元素特定状态或位置的强大工具,它们允许开发者根据元素的特定状态(如点击、悬停、激活等)或位置(如第一个子元素、最后一个子元素等)来应用样式,本文将详细介绍CSS3中常用的伪类选择器及其用法。

一、动态伪类选择器

动态伪类选择器根据用户与元素的交互状态来选择元素,以下是几个常用的动态伪类选择器:

1. `:link`:选择未被访问的链接。

a:link {
  color: blue;
}

2. `:visited`:选择已被访问的链接。

a:visited {
  color: purple;
}

出于隐私和安全考虑,现代浏览器对`:visited`选择器的样式应用进行了限制,以防止通过颜色等样式泄露用户的浏览历史。

3. `:hover`:选择鼠标指针悬停在元素上的状态。

button:hover {
  background-color: yellow;
}

4. `:active`:选择元素被激活时的状态,如鼠标点击时(但尚未释放)。

button:active {
  background-color: red;
}

5. `:focus`:选择获得焦点的元素,通常用于表单元素。

input:focus {
  outline: none;
  border: 2px solid green;
}
二、结构性伪类选择器

结构性伪类选择器根据元素在文档树中的位置来选择元素,以下是几个常用的结构性伪类选择器:

1. `:first-child`:选择其父元素的第一个子元素。

ul li:first-child {
  color: red;
}

2. `:last-child`:选择其父元素的最后一个子元素。

ul li:last-child {
  color: blue;
}

3. `:nth-child(n)`:选择其父元素的第n个子元素,n可以是数字、关键词(如even、odd)或公式(如2n+1)。

ul li:nth-child(2) {
  color: green;
}

ul li:nth-child(even) {
  background-color: lightgray;
}

4. `:nth-last-child(n)`:选择其父元素的倒数第n个子元素,与`:nth-child(n)`类似,但计数方向相反。

ul li:nth-last-child(2) {
  font-weight: bold;
}

5. `:only-child`:选择其父元素仅有一个子元素的元素。

div p:only-child {
  color: orange;
}

6. `:only-of-type`:选择在其父元素中同类型元素中唯一的元素。

div p:only-of-type {
  font-size: 20px;
}

7. `:first-of-type` 和 `:last-of-type`:分别选择其父元素中同类型元素中的第一个和最后一个元素。

div p:first-of-type {
  margin-top: 0;
}

div p:last-of-type {
  margin-bottom: 0;
}
三、UI元素状态伪类选择器

UI元素状态伪类选择器用于选择处于特定状态的UI元素,如启用、禁用、选中、未选中等,以下是几个常用的UI元素状态伪类选择器:

1. `:enabled`:选择启用的表单元素。

input:enabled {
  background-color: white;
}

2. `:disabled`:选择禁用的表单元素。

input:disabled {
  background-color: gray;
}

3. `:checked`:选择被选中的表单元素(如radio按钮、checkbox等)。

input[type="checkbox"]:checked {
  border: 2px solid green;
}

4. `:default`:选择默认选中的表单元素(如radio按钮组中的默认选中项)。

input[type="radio"]:default {
  font-weight: bold;
}
四、否定伪类选择器

`:not()` 是一个否定伪类选择器,用于排除某些元素,它接受一个选择器作为参数