CSS3 新增伪类选择器

100 阅读1分钟

1. empty 选择器

empty 选择器用于选择没有任何子元素(包括文本节点)的元素。例如:

p:empty {
  color: red;
}

这个选择器会将没有任何内容的 <p> 元素的文本颜色设置为红色。

2. :root 选择器

:root 选择器表示文档的根元素。在HTML中,根元素通常是 <html>。例如:

:root {
  --main-color: #06c;
}

这个选择器可以用于定义CSS变量。

3. :target 选择器

:target 选择器用于选择当前活动的目标元素。它通常用于页面锚点链接。例如:

:target {
  background-color: yellow;
}

当用户点击一个链接并跳转到页面中的某个部分时,目标部分的背景颜色会变为黄色。

代码示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Target Selector Example</title>
    <style>
        /* 使用 :target 选择器 */
        :target {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <h1>Target Selector Example</h1>
    <p><a href="#section1">Go to Section 1</a></p>
    <p><a href="#section2">Go to Section 2</a></p>
    <p><a href="#section3">Go to Section 3</a></p>

    <div id="section1">
        <h2>Section 1</h2>
        <p>This is section 1.</p>
    </div>

    <div id="section2">
        <h2>Section 2</h2>
        <p>This is section 2.</p>
    </div>

    <div id="section3">
        <h2>Section 3</h2>
        <p>This is section 3.</p>
    </div>
</body>
</html>

屏幕截图 2024-06-06 223400.png