首页 > 技术文章 > CSS中的伪类

rans 2020-04-29 16:16 原文

1.动态伪类

 :link(未访问),:visited(已访问),:hover(经过),:active(点击时),:focus(获取焦点时)

 顺序:link-> visited-> focus-> hover-> avtive

/* :hover 和 :active 除了在 a 元素中可以使用,也可以在其他元素中使用 */
strong:hover{
    color:red;
}
<strong> 这是一个 strong 元素内容</strong>

扩展:

 focus伪类常用与 input 元素中,a 元素中也可以使用 focus 伪类

 a 元素使用 tab 键时,会有焦点状态,去除 a 元素的焦点状态

方式一:(去除轮廓线(并没有真正去除焦点状态))

a:focus{
    outline:none;
}

方式二:(通过 tabindex,可以调整 tab 的选中元素的顺序)

<a tabindex='-1' href='#'>Google一下</a>

2.目标伪类(不常用)

 :target

/* 一般用于锚点链接,当点击 a 标签跳转到某个锚点位置,更改锚点位置的样式 */
:target{
    color:red;
}

3.语言伪类(不常用)

 :lang()

4.元素状态伪类(不常用)

 :enabled(可用),:disabled(禁用),:checked(被选中)

5.结构伪类

 :nth-child(n)(在所有子元素中查找第n个子元素)

 :nth-last-child(n)(从后向前查找第n个子元素)

 div:nth-of-type(n)(只查找 div 类型的第 n 个子元素)

 :nth-last-of-type(n)(从后向前查找 指定类型的第 n 个子元素)

 

 :first-child 等同于 :nth-child(1)

 :last-child  等同于 :nth-last-child(1)

 :first-of-type 等同于 :nth-of-type(1)

 :last-of-type 等同于 :nth-last-of-type(1)

 

 :only-child 父元素中唯一的子元素

 :only-of-type 父元素中唯一的这种类型的子元素

 :root 根元素,就是HTML元素

 :empty 内容完全空白的元素

6.否定伪类

 :not(x)

:not(div){
    color:red;
}
/* 除 div 之外的其他元素字体颜色是红色 */

 

推荐阅读