CSS - 伪类


CSS 中的伪类用于根据元素在文档树中的状态或位置来选择元素并设置元素样式,而无需向 HTML 元素添加额外的类或 ID。这些伪类主要用于在网页中创建交互式和动态样式。

句法

selector:pseudo-class { property: value; }
  • 伪类以冒号 (:) 开头,后面是选择器。例如:: hover、:focus等。

  • 函数伪类包含一对括号来定义参数。例如::lang()

  • 附加伪类的元素称为锚元素。例如:button:hover、a:focus等。这里button和a元素称为锚元素。

  • 伪类根据文档树的内容将样式应用于元素。

  • 伪类还将与外部因素相关的样式应用于元素,例如元素导航的历史记录 ( : visited )、内容的状态 ( :checked ) 或鼠标位置 ( :hover )

与对整个元素设置样式的伪类不同,伪元素针对元素的特定部分并设置其样式。

就像常规类一样,您可以灵活地在单个选择器中组合多个伪类。

元素显示状态伪类

诸如:fullscreen、:modal:picture-in-picture 之类的伪类是根据元素的显示状态定位和设置元素样式的伪类。

这是:fullscreen伪类的示例:

<html> <head> <style> .sample { padding: 10px; height: 200px; width: 95%; background-color: lightgrey; } .sample p { visibility: hidden; text-align: center; color: black; font-size: 2em; } .sample:fullscreen { background-color: lightsalmon; width: 100vw; height: 100vh; } .sample:fullscreen p { visibility: visible; } </style> </head> <body> <h2>:fullscreen example</h2> <div class="container"> <div class="sample" id="sample"> <p>Fullscreen mode</p> </div> <br> <button onclick="var el=document.getElementById('sample'); el.webkitRequestFullscreen();">Click here</button> </div> </body> </html>

这是:modal伪类的示例:

<html> <head> <style> ::backdrop { background-image: url(border.png); } :modal { border: 8px inset blue; background-color: lightpink; box-shadow: 3px 3px 10px rgba(0 0 0 / 0.5); } </style> </head> <body> <dialog> <button autofocus>Close</button> <p>The modal dialog has a beautiful backdrop!</p> <p>And see my styling using :modal pseudo-class</p> </dialog> <button>Open the dialog</button> <script> const dialog = document.querySelector("dialog"); const showButton = document.querySelector("dialog + button"); const closeButton = document.querySelector("dialog button"); // "Show the dialog" button opens the dialog modally showButton.addEventListener("click", () => { dialog.showModal(); }); // "Close" button closes the dialog closeButton.addEventListener("click", () => { dialog.close(); }); </script> </body> </html>

输入伪类

伪类以<input>元素为目标并对其进行样式设置,并允许基于 HTML 属性选择元素,以及元素在用户交互之前和之后的状态,如以下部分中的示例所示。

这是:autofill伪类的示例:

<html> <head> <style> label { display: block; margin-top: 1em; } input { border: 3px solid grey; border-radius: 3px; } input:-webkit-autofill { border: 3px solid green; background-color: yellow; } input:autofill { border: 3px solid green; background-color: yellow; } </style> </head> <body> <h3>:autofill example</h3> <form method="post" action=""> <label for="name">First Name</label> <input type="first-name" id="name" /> <label for="name">Last Name</label> <input type="last-name" id="name" /> <label for="email">Email</label> <input type="email" name="email" id="email" autocomplete="email" /> </form> </body> </html>

这是:enabled伪类的示例:

<html> <head> <style> input[type=text]:enabled { background: white; } input[type=text]:disabled { background: lightgrey; } input { width: 150px; padding-left: 10px; margin-top: 10px; border: 1px solid black; } form { border: 2px solid black; width: 300px; padding: 10px; } </style> </head> <body> <h2>:enabled example</h2> <form action=""> <label>First Name</label> <input type="text"><br> <label>Last Name</label> <input type="text"><br> <label>Address</label> <input type="text" disabled="disabled" value="Address"><br><br> <button type="submit" disabled="disabled">Submit</button> <button type="reset">Reset</button> </form> </body> </html>

这是:disabled伪类的示例:

<html> <head> <style> input[type=text]:enabled { background: white; } input[type=text]:disabled { background: lightgrey; } input { width: 150px; padding-left: 10px; margin-top: 10px; border: 1px solid black; } </style> </head> <body> <h2>:disabled example</h2> <form action=""> <label>Doctor Name</label> <input type="text"><br> <label>Hospital Name</label> <input type="text"><br> <label>Diagnosis</label> <input type="text" disabled="disabled" value="Diagnosis"><br><br> <button type="submit" disabled="disabled">Submit</button> <button type="reset">Reset</button> </form> </body> </html>

其他这样的伪类有 : :read-only, :read-write, :placeholder-shown, :default, :checked, :inminate, :blank, :valid, :invalid, :in-range, :out-of-范围、:必需、:可选:用户无效

语言伪类

反映文档语言并能够根据语言或脚本的方向选择元素的伪类就属于这一类。

这是:lang()伪类的示例:

<html> <head> <style> :lang(en) > q { quotes: '""'; } :lang(fr) > q { quotes: '« ' ' »'; color: white; background-color: steelblue; } div { padding: 10px; } </style> </head> <body> <h2>:lang() selector example</h2> <div lang="en"> <q>Lorem ipsum is simply dummy text</q> </div> <div lang="fr"> <q>Lorem ipsum is simply dummy text</q> </div> </body> </html>

位置伪类

与同一当前文档中的链接和目标元素相关的伪类属于此类伪类。

它们是:any-link、:link、:visited、:target:scope。下面显示了一些示例。

以下是使用:any-link更改链接的前景色和背景色的示例:

<html> <head> <style> div { padding: 5px; border: 2px solid black; margin: 1em; width: 500px; } a:any-link { font-weight: 900; text-decoration: none; color: green; font-size: 1em; } .with-nohref { color: royalblue; } .with-empty { color: crimson; } </style> </head> <body> <h3>:any-link example</h3> <div> anchor elements with href to tutorialspoint.com-- <a href="https://tutorialspoint.com">click here</a> </div> <div> <a class="with-nohref">with no href</a> </div> <div> <a href="#" class="with-empty">with empty href</a> </div> </body> </html>

下面是:link伪类和:hover伪类的示例:

<html> <head> <style> a { font-size: 1em; padding: 5px; display: inline-block; margin-right: 10px; } a:link { background-color: lightyellow; } a:hover { background-color: lightsalmon; color: green; } </style> </head> <body> <h2>:link selector example</h2> <strong><a href="https://www.tutorialspoint.com">Tutorialspoint</a></strong> <strong><a href="https://www.google.com">Google</a></strong> </body> </html>

树结构伪类

根据元素在文档树中的位置来定位元素的伪类属于此类伪类。

它们是:root、:empty、:nth-child、:nth-last-child、:first-child、:last-child、:only-child、:nth-of-type、:nth-last-of-type 、 :first-of-type、 :last-of-type:only-of-type。下面显示了一些示例。

以下是:empty伪类的示例,应用于 <p> 标记:

<html> <head> <style> p:empty { width: 200px; height: 30px; background: magenta; } div { border: 3px solid black; width: 300px; text-align: center; } </style> </head> <body> <h2>:empty example</h2> <div> <p>Not an empty paragraph</p> <p></p> <p>Not an empty paragraph</p> </div> </body> </html>

以下是:first-child伪类的示例,应用于 <div> 父元素下的 <p> 标记。在此示例中,CSS 规则仅适用于 <div> 元素中找到的第一个 <p> 元素,同一容器中的其他 <p> 元素不受影响。

<html> <head> <style> p:first-child { color: black; background: yellow; font-weight: 600; font-size: 1em; font-style: italic; padding: 5px; } div { border: 2px solid black; margin-bottom: 5px; } </style> </head> <body> <div>Parent element <p>first child looks different due to :first-child pseudo-class</p> <p>second child, so no change</p> </div> <div>Parent element <h2>h3 tag, so no change</h2> <p><p> tag, but not the first child.</p> </div> </body> </html>

以下是:only-of-type伪类的示例,应用于 <div> 父元素下的 <p> 和 <h2> 标记。在此示例中,CSS 规则仅适用于 <div> 父容器中的 <p> 和 <h2> 类型元素。

<html> <head> <style> .field { margin: 1px; padding: 1px; } p:only-of-type { color: darkblue; background-color: lightpink; padding: 5px; } h2:only-of-type { text-decoration-line: underline; color: green; } div { border: 2px solid black; width: 500px; } </style> </head> <body> <div class="field"> <h2>Heading 2 - only type</h2> <p>Paragraph tag - only type</p> </div> <div class="field"> <h2>Heading 2 - only type</h2> <p>Paragraph tag 1 - we are two</p> <p>Paragraph tag 2 - we are two</p> </div> </body> </html>

用户操作伪类

所有这些伪类都需要一些用户交互或干预才能应用规则或样式,例如单击输入字段或将鼠标悬停在按钮上等。

这些伪类是:active、:focus、:focus-visible、:focus-within:hover。下面显示了一些示例。

下面是一个将焦点设置在链接上的示例:

<html> <head> <style> a { color: darkviolet; transition: all 0.3s ease; } a:focus { outline: none; color: red; background-color: yellow; } body { margin: 5px; padding: 2rem; display: grid; font: 20px/1.4 system-ui, -apple-system, sans-serif; } </style> </head> <body> <p>The link here has a <a href="#0">change in background and foreground color</a> as it is focussed.</p> </body> </html>

下面是一个示例,其中焦点设置在输入字段上,使用:focus-within将焦点设置在其标签上:

<html> <head> <style> label { display: block; font-size: 20px; color: black; width: 500px; } input[type="text"] { padding: 10px 16px; font-size: 16px; color: black; background-color: #fff; border: 1px solid #597183; border-radius: 8px; margin-top: 5px; width: 500px; transition: all 0.3s ease; } input[type="text"]:focus { background-color: lightyellow; } label:focus-within { font-size: 25px; color: red; } </style> </head> <body> <form> <label> Full Name <input type="text"> </label> </form> </body> </html>

下面是使用:active伪类更改按钮的边框、前景色和背景色的示例:

<html> <head> <style> div { padding: 1rem; } button { background-color: greenyellow; font-size: large; } button:active { background-color: gold; color: red; border: 5px inset grey; } </style> </head> <body> <h3>:active example - button</h3> </div> <button>Click on me!!!</button> </div> </body> </html>

函数式伪类

列出的伪类充当函数并接受选择器列表或宽容选择器列表作为参数。它们是:is()、:has()、:not():where()

下面是:is()函数伪类的示例,其中 :is 伪类应用于 h1、h2、h3 和 a 等元素。因此,无论在哪里找到这些元素,都会应用适当的样式:

<html> <head> <style> body { font: 300 90%/1.4 system-ui; margin: 1rem; } main :is(h1, h2, h3) { color: green; } main :is(a) { color: red; font-size: large; } </style> </head> <body> <main> <h1>:is() pseudo-class example</h1> <h3>Li Europan lingues</h3> <a href="">es membres del sam familie</a>. <p>Lor separat existentie es un myth.</p> <h2>Por scientie, musica, sport etc, litot Europa usa li sam vocabular.</h2> <p>Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores.</p> <p>At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles.</p> <h3>Ma quande lingues coalesce</h3> <p>li grammatica del resultant lingue es plu simplic e regulari quam ti del coalescent lingues. Li nov lingua franca va esser plu simplic e regulari quam li existent Europan lingues.</p> <p>It va esser tam simplic quam <a href="">Occidental</a> in fact, it va esser Occidental.</p> </main> </body> </html>

以下是:not()伪类的示例,其中由于:not(h1) ,使用.sample类定义的样式未应用于 h1 元素:

<html> <head> <style> .sample { text-shadow: 2px 2px 3px yellow; } /* <h1> elements that are not in the class '.sample' */ h1:not(.sample) { background-color: lightblue ; } /* Elements that are not <h1> elements */ body :not(h1) { text-decoration-line: line-through; } /* Elements that are not <div> and not <span> elements */ body :not(div):not(span) { font-weight: bold; } </style> </head> <body> <h1>heading with :not(.sample) pseudo-class applied</h1> <h1 class="sample">heading with styling applied</p> <p>Paragraph, hence :not(h1) and :not(div):not(span) applied.</p> <div>div element, hence :not(h1) applied.</div> </body> </html>

下表列出了所有 CSS 伪类:

伪类 描述 例子
:积极的 表示已被用户激活的元素。 a:活动{}
:任意链接 表示充当超链接的源锚点的元素,与是否已被访问无关。 a:任意链接{}
:自动填充 匹配由浏览器自动填充其值的元素。 输入:自动填充{}
:检查过 匹配任何已选中或切换的单选、复选框或选项元素。 输入:选中{}
:默认 选择一组相关元素中默认的表单元素。 输入:默认{}
:定义 代表已定义的任何元素。 <自定义元素>:定义{}
:禁用 代表一个被禁用的元素。 输入:禁用{}
:空的 匹配没有子元素的元素。 div:空{}
:启用 表示激活后的启用元素。 输入:启用{}
:第一的 表示打印文档的第一页,带有 @page at 规则。 @页面:第一页{}
:第一个孩子 表示一组同级元素中的第一个元素。 li:第一个孩子{}
: 首创型 表示一组同级元素中该类型的第一个元素。 p:第一个类型{}
:全屏 匹配当前以全屏模式显示的元素。 #id:全屏{}
:重点 表示已获得焦点的元素。 输入:焦点{}
:焦点-可见 当元素匹配 :focus 伪类或接收焦点时应用。 输入:焦点可见{}
: 焦点内 如果某个元素或其任何后代获得焦点,则匹配该元素。 标签:焦点内{}
:主持人 这会选择包含在其中使用的 CSS 的影子 DOM 的影子主机。 :主持人{}
:主持人() 此函数选择包含在其中使用的 CSS 的影子 DOM 的影子主机。 :主持人()
:主机上下文() 此函数允许您根据其祖先元素的类或属性来设置自定义元素的样式。 :主机上下文()
:徘徊 当用户使用指针设备(例如鼠标)与元素交互时匹配,但不一定激活它。 按钮:悬停{}
:不定 表示状态不确定或未知的任何表单元素。 输入:不确定{}
:在范围内 表示当前值在范围限制内的元素。 输入:范围内{}
:无效的 表示其内容无法验证的任何元素。 输入:无效{}
:是() 将选择器列表作为其参数,并选择可由该列表中的选择器之一选择的任何元素。 :is(ol, ul){}
:郎() 根据定义的语言来匹配元素。 *:lang(en){}
:最后一个孩子 表示一组同级元素中的最后一个元素。 li:最后一个孩子{}
:最后一个类型 表示一组同级元素中该类型的最后一个元素。 p:最后一个类型{}
:左边 表示打印文档的所有左侧页面,与 @page at-rule 一起使用。 @页:左{}
:关联 表示尚未被访问过的元素。 一条链接{}
:模态 匹配处于排除与其外部元素的所有交互直到交互被消除的状态的元素。 :模态{}
:不是() 表示与选择器列表不匹配的元素。 p:不(强){}
:第n个孩子() 根据子元素在父元素内所有同级元素中的位置选择子元素。 li:第 n 个子级 (-n+3){}
:第n个最后一个孩子() 根据元素在兄弟元素中的位置进行匹配,从最后一个(末尾)开始计数 li:第 n 个最后一个子节点(奇数){}
:nth-last-of-type() 根据元素在相同类型的同级元素中的位置进行匹配,从最后一个(末尾)开始计数。 dd:第 n 个最后类型(3n){}
:nth-of-type() 根据元素在相同类型的同级元素中的位置来匹配元素。 dd:第 n 个类型(偶数){}
:唯一的孩子 表示没有任何兄弟元素的元素。 li:独生子女{}
: 仅限类型 表示没有相同类型同级的元素。 a:仅限类型{}
:选修的 表示未设置必需属性的元素。 输入:可选{}
:超出范围 表示当前值超出范围限制的元素。 输入:超出范围{}
: 画中画 匹配当前处于画中画模式的元素。 :画中画{}
:占位符显示 表示当前显示占位符文本的任何元素。 输入:显示占位符{}
:只读 表示用户不可编辑的元素。 文本区域:只读{}
:读写 表示可由用户编辑的元素。 文本区域:读写{}
:必需的 表示设置了必需属性的元素。 输入:必需{}
:正确的 表示打印文档的所有右侧页面,与 @page at-rule 一起使用。 @页:右{}
:根 匹配文档树的根元素。 :根{}
:范围 表示作为选择器匹配的参考点或范围的元素。 :范围{}
:目标 表示具有与 URL 片段匹配的 id 的目标元素。 p:目标{}
:有效的 表示其内容验证成功的任何元素。 输入:有效{}
:访问过 链接被访问后即适用。 a:访问过{}
:在哪里() 将选择器列表作为其参数并选择任何匹配的元素。 :where(ol, ul){}