css伪类就是元素的一种特殊状态,下面的伪类是相关的,可以尝试其中的示例代码看看实际效果。
需要按照 LVHA 的顺序定义样式,否则 active 的样式可能会被覆盖。
link 是链接的初始状态,visited 是链接访问过(点击)之后的状态,hover 是鼠标悬停的状态,active 是激活状态(鼠标主键按下及松开之间的状态)。
any-link 就是 link 和 visited 状态的集合, local-link(实验性的)一般表示锚点链接,指向当前文档。
设置了 autocomplete 属性的表单元素会在获取焦点后有浏览器提示,当选中浏览器提示时触发 autofill 状态。
这是实验性的,表示 input 或 textarea 元素非必填且为空的状态。
表示 checkbox, radio, select 下的 option 选中时的状态。
这是实验性的,目前基本没用。在 video 元素内部使用 track 元素,该元素引入的文件就是 WEBVTT 字幕轨道。
表示设置了 checked 属性的 checkbox 和 radio 元素,设置了 selected 属性的 option 元素,表单的默认提交按钮(type=submit)。
表示浏览器内置标准元素以及customElements.define()定义的自定义元素。
dir 伪类会继承父级的文本方向,:dir(ltr | rtl)的选择器元素即使没有设置 dir 属性也会生效。
在元素设置lang="属性后,可以使用:lang(选中元素。
表单元素 input,select,textarea,button 可以设置 disabled 属性实现disabled状态。没有 disabled 属性或者 disabled=false 就是enabled状态。
元素内部不存在元素节点和文本节点就认为是empty状态。注释节点不包括。
<style>
div:empty {
outline: 2px solid deeppink;
height: 1em;
}
style>
<p>Element with no content:p>
<div>div>
<p>Element with comment:p>
<div>div>
<p>Element with whitespace:p>
<div> div>
伪类的样式只会生效的属性有
margin, padding, border, background。
:first和@page一起使用,选中被打印文档的第一页。:left或:right和@page一起使用,选中被打印文档的左手边页面或右手边页面。一般双面打印的正面是右手边页面,背面是左手边页面。
/* Selects the first page when printing */
@page :first {
margin-left: 50%;
margin-top: 50%;
}
first-child和last-child分别选中同级兄弟元素的第一个和最后一个元素,并且元素必须与选择器匹配。
<style>
p:first-child {
color: lime;
background-color: black;
padding: 5px;
}
style>
<div>
<p>This text is selected!p>
<p>This text isn't selected.p>
div>
<div>
<h2>This text isn't selected: it's not a `p`.h2>
<p>This text isn't selected.p>
div>
first-of-type和last-of-type选中同级兄弟元素的第一种类的元素,后一个从末尾倒数,如果选择器不存在则默认是通用选择器(*)。
<style>
/* article下的所有同级兄弟元素的第一个被选中 */
article :first-of-type {
background-color: pink;
}
style>
<article>
<div>This `div` is first!div>
<div>This <span>nested `span` is firstspan>!div>
<div>This <em>nested `em` is firstem>, but this <em>nested `em` is lastem>!div>
<div>This <span>nested `span` gets styledspan>!div>
<p>This `p` qualifies!p>
<div>This is the final `div`.div>
article>
当浏览器开启全屏之后,document.fullscreenElement的值就是:fullscreen选中的元素。
表单元素以及其它可以通过 Tab 键选中的元素在用户点击时会进入 focus 状态。
focus-visible状态包含focus状态,只不过focus-visible状态存在由用户代理启发式设置的默认样式对焦环。
/* user agent stylesheet */
:focus-visible {
outline: -webkit-focus-ring-color auto 1px;
}
focus-within状态表示选择器自身符合focus状态或者选择器元素的后代元素符合focus状态。
<style>
form {
border: 1px solid;
color: gray;
padding: 4px;
}
form:focus-within {
background: #ff8;
color: black;
}
style>
<form>
<label for="given_name">Given Name:label>
<input id="given_name" type="text" />
<br