什么是伪类?

伪类用于定义元素的特殊状态。 例如,它可用于:

  • 当用户将鼠标悬停在元素上时为其设置样式
  • 访问和未访问的链接不同样式
  • 在获得焦点时设置元素的样式

伪类的语法

后代选择器匹配作为指定元素后代的所有元素。以下示例选择<div>元素内的所有<p>元素:

选择器:伪类 { 属性:值; }

链接可以以不同方式显示:

/* 未访问的链接 */ 
a:link {   color: red; } 
/* 已浏览过的链接 */
 a:visited {   color: green; } 
/* 鼠标悬停时候的链接 */ 
a:hover {   color: hotpink; }
 /* 选定的链接 */ 
a:active {   color: blue; }

 

注意:a:hover必须在CSS定义a:link之后和a:visited之后才能生效!a:active必须 a:hover在CSS定义之后才能有效!伪类名称不区分大小写。

伪类和CSS类

伪类可以与CSS类结合使用:当您将鼠标悬停在示例中的链接上时,它将更改颜色:

a.highlight:hover { color: #ff0000; }

将鼠标悬停在<div>上

:hover在<div>元素上使用伪类的示例:

div:hover { background-color: blue; }

简单的工具提示悬停

将鼠标悬停在<div>元素上以显示<p>元素(如工具提示)

p {display: none;background-color: yellow;padding: 20px; } 
div:hover p {display: block; }

:first-child伪类

:first-child伪类指定的元素是另一个元素的第一个子匹配。 在以下示例中,选择器匹配任何元素的第一个子元素<p>元素:

p:first-child { color: blue; }

匹配所有<p>元素中的第一个元素

p i:first-child { color: blue; }

匹配所有第一个子<p>元素中的所有元素

p:first-child i { color: blue; }

:lang伪类

:lang伪类允许定义不同语言的特殊规则。在下面的示例中,:lang使用lang=“no”定义<q>元素的引用:

q:lang(no) { quotes: "~" "~"; }

所有CSS伪类

选择器例子描述
:active a:active 选择active激活链接
:checked input:checked 选择每个选中的<input>元素
:disabled input:disabled 选择每个禁用的<input>元素
:empty p:empty 选择每个没有子元素的<p>元素
:enabled input:enabled 选择每个启用的<input>元素
:first-child p:first-child 选择作为其父级的第一个子元素的每个<p>元素
:first-of-type p:first-of-type 选择每个<p>元素,它是其父元素的第一个<p>元素
:focus input:focus 选择具有焦点的<input>元素
:hover a:hover 选择鼠标悬停时的链接
:in-range input:in-range 选择具有指定范围内的值的<input>元素
:invalid input:invalid 选择具有无效值的所有<input>元素
:lang(language) p:lang(it) 选择具有以“it”开头的lang属性值的每个<p>元素
:last-child p:last-child 选择作为其父级的最后一个子元素的每个<p>元素
:last-of-type p:last-of-type 选择每个<p>元素,它是其父元素的最后一个<p>元素
:link a:link 选择所有未访问的链接
:not(selector) :not(p) 选择不是<p>元素的每个元素
:nth-child(n) p:nth-child(2) 选择作为其父级的第二个子元素的每个<p>元素
:nth-last-child(n) p:nth-last-child(2) 选择每个<p>元素作为其父元素的第二个子元素,从最后一个子元素开始计算
:nth-last-of-type(n) p:nth-last-of-type(2) 选择每个<p>元素作为其父元素的第二个<p>元素,从最后一个子元素开始计算
:nth-of-type(n) p:nth-of-type(2) 选择每个<p>元素,它是其父元素的第二个<p>元素
:only-of-type p:only-of-type 选择每个<p>元素,它是其父元素的唯一<p>元素
:only-child p:only-child 选择每个<p>元素,它是其父元素的唯一子元素
:optional input:optional 选择没有“required”属性的<input>元素
:out-of-range input:out-of-range 选择<input>元素,其值超出指定范围
:read-only input:read-only 选择具有指定“readonly”属性的<input>元素
:read-write input:read-write 选择没有“readonly”属性的<input>元素
:required input:required 选择指定了“required”属性的<input>元素
:root root 选择文档的根元素
:target #news:target 选择当前活动的#news元素(单击包含该锚名称的URL)
:valid input:valid 选择具有有效值的所有<input>元素
:visited a:visited 选择所有访问过的链接

所有CSS伪元素

选择器例子描述
::after p::after 在每个<p>元素后插入内容
::before p::before 在每个<p>元素之前插入内容
::first-letter p::first-letter 选择每个<p>元素的第一个字母
::first-line p::first-line 选择每个<p>元素的第一行
::selection p::selection 选择用户选择的元素部分
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!