CSS 选择器:完整参考指南 🚀 目录 CSS 中的选择器是什么?选择器的类型 分组选择器 组合选择器 伪类 伪元素

2025-05-28

CSS 选择器:完整参考指南🚀

目录

CSS 中的选择器是什么?

选择器的类型

分组选择器

组合选择器

伪类

伪元素

大家好!🚀

今天我们将深入介绍 CSS 选择器。


目录


CSS 中的选择器是什么?

CSS 选择器是一种用于选择我们想要设置样式的HTML 元素的模式

更专业地讲,CSS 选择器能够选择将应用样式规则集的 HTML 元素

选择器的类型

1. 通用选择器

语法: * { 样式属性 }

该选择器用星号(*)表示,与HTML 文档中的所有元素匹配。

<ul>
  <li>Computer Science Eng.</li>
  <li>Mathematics</li>
  <li>Physics</li>
</ul>
Enter fullscreen mode Exit fullscreen mode
* {
  border: 1px solid coral;
}
Enter fullscreen mode Exit fullscreen mode

这将对文档中的所有元素应用 1px 实心珊瑚边框。

输出:
替代文本

border 属性很好地展现了这个选择器的行为。正如上图所示,现在每个元素都被边框包围了,包括<body>元素本身和<html>元素之外。


通用选择器也用于避免混淆并使您的代码更易于阅读

我们来看以下例子:

div :first-child {
  background-color: maroon;
}
Enter fullscreen mode Exit fullscreen mode
div:first-child {
  background-color: maroon;
}
Enter fullscreen mode Exit fullscreen mode

这两个代码片段看起来几乎相同,对吗?

好吧,我们只需要注意类型选择器和伪类之间的空白就可以意识到它们并不完全相同:第一个选择每个<div>元素的第一个子元素,第二个选择<div>本身是另一个元素的第一个子元素的元素。

先别慌,我们稍后会更详细地讨论伪类以及选择器的工作原理🙂

现在,只需记住,在这个例子中,有两个不同的元素选择器协同工作来应用样式规则。稍后一切都会明白。我保证。

无论如何,为了区分彼此,并且能够更清楚地看到空白,我们可以使用通用选择器,如下所示:

div *:first-child{
  background-color: maroon;
}
Enter fullscreen mode Exit fullscreen mode

从功能角度来说,添加星号并没有什么作用,但它有助于快速识别要定位的元素并保持代码整洁

2. 类型选择器

语法: elemType { 样式属性 }

此选择器匹配属于指定类型的所有元素

<p>A paragraph</p>
<p>Another paragraph</p>
<p>One more paragraph</p>
Enter fullscreen mode Exit fullscreen mode
p {
  font-size: 1.5rem;
  color: deeppink;
}
Enter fullscreen mode Exit fullscreen mode

这将为所有元素应用 1.5rem 的字体大小和深粉色<p>。简单直接。

输出:
替代文本

3. 类选择器

语法: .classname { 样式属性 }

该选择器以句点(.)表示,匹配所有包含指定类的元素

<div>
  <p class="deeppink">This is a deep pink paragraph</p>
  <p class="hotpink">This is a hot pink paragraph</p>
  <p class="pink">This is a regular pink paragraph</p>
  <p class="deeppink-bg">This is a paragraph with a deep pink background</p>
  <p class="hotpink-bg">This is a paragraph with a hot pink background</p>
  <p class="pink-bg">This is a paragraph with a regular pink background</p>
</div>
Enter fullscreen mode Exit fullscreen mode
.deeppink {
  color: deeppink;
}
.hotpink {
  color: hotpink;
}
.pink {
  color: pink;
}
.deeppink-bg {
  background-color: deeppink;
}
.hotpink-bg {
  background-color: hotpink;
}
.pink-bg {
  background-color: pink;
}

/* Group selector - Stay until the end to understand its
 behavior 😉 */
.deeppink-bg, .hotpink-bg, .pink-bg {
  color: white;
}

Enter fullscreen mode Exit fullscreen mode

这将根据元素所包含的类为每个元素应用不同的粉红色变体<p>,并为其文本或背景设置样式。

输出:

替代文本


指定类选择器的另一种方法是将包含类名的元素的类型附加在常规类选择器前面。

看一下这个常规列表的示例:

<ul>
  <li class="list-item">...</li>
  <li class="list-item">...</li>
  <li class="list-item">...</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

我们可以像这样设置每个列表项的样式:

.list-item{
  padding: 5px;
}
Enter fullscreen mode Exit fullscreen mode

或者像这样:

li.list-item{
  padding: 5px;
}
Enter fullscreen mode Exit fullscreen mode

请注意,在这种特定情况下,没有必要使用此方法,因为所有包含list-item类的元素都是<li>元素,因此附加元素类型不会产生任何区别。

但是让我们看看下面的另一个例子:

<section>
 <h1 class="big">List of animals</h1>
 <ul>
   <li><p class="big">Cat</p></li>
   <li><p class="big">Dog</p></li>
   <li><p class="big">Monkey</p></li>
   <li><p class="big">Dolphin</p></li>
   <li><p class="big">Frog</p></li>
 </ul>
</section>
Enter fullscreen mode Exit fullscreen mode

在此示例中,我们有不同类型的元素引用同一个类,因此,为了对每个元素应用不同的样式规则,我们需要指定包含该类的元素的类型。否则,这些元素将无法正确定位,最终导致我们尝试应用的样式无法按预期显示。

因此,我们应该执行以下操作来根据元素是标题还是段落来应用不同的规则:

h1.big {
  font-size: 3rem;
  color: coral;
}

p.big {
  font-size: 2rem;
  color: orange;
}
Enter fullscreen mode Exit fullscreen mode

输出:
替代文本

4. ID 选择器

语法: #idname { 样式属性 }

该选择器由井号 (#)表示,并匹配包含指定 id 的唯一元素

<div>
  <table id="users-table">
    <th>Users</th>
    <tr>
      <td>John Doe</td>
    </tr>
    <tr>
      <td>Jane Doe</td>
    </tr>
  </table>
  <table id="staff-table">
    <th>Staff</th>
    <tr>
      <td>Hannah Legend</td>
    </tr>
    <tr>
      <td>Daniel Oaks</td>
    </tr>
  </table>
</div>
Enter fullscreen mode Exit fullscreen mode
/* Type selector */
table {
  padding: 20px;
}
/* ID selectors */
#users-table {
  background-color: black;
  color: white;
}
#staff-table {
  border: 1px solid black;
}
Enter fullscreen mode Exit fullscreen mode

这将为 id 为users-table 的表格应用黑色背景和白色文本,并为 id 为staff-table的表格应用 1px 的纯黑色边框。根据其类型,它们都获得了 20px 的填充。

输出:

替代文本

重要提示:尽管 HTML 允许您为多个元素分配相同的 id 值,但您不应该这样做

如果需要将相同的样式应用于一堆不同的元素,请始终使用 class 属性。这样可以保持代码整洁,并避免可能出现的混淆。

5. 属性选择器

属性选择器比其他选择器更复杂,并且具有多种语法,可以根据它们应满足的条件应用于我们的 HTML 元素。

换句话说,它匹配所有包含指定属性且该属性的值满足给定条件的HTML 元素。

属性选择器语法

语法 1

[attr] { 样式属性 }

匹配具有指定属性的元素

<nav>
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="/blog">Blog</a></li>
    <li><a href="/contact">Contact</a></li>
    <li><a href="/about">About</a></li>
  </ul>
</nav>
Enter fullscreen mode Exit fullscreen mode
/* Type selector */
nav {
  background-color: darkslategray;
  padding: 10px;
}

/* Attribute selector */
a[href] {
  color: white;
  text-decoration: none;
}

Enter fullscreen mode Exit fullscreen mode

<a>这将对包含该属性的每个元素应用白色href,无论其值如何,并删除下划线。

我们还<nav>通过使用类型选择器来为元素设置背景颜色和一些填充样式。

输出:

替代文本

语法 2

[attr=value] { 样式属性 }

匹配attr正好是 value的元素

<form>
  <label for="username">Username</label>
  <input id="username" type="text" placeholder="Username" />
  <label for="password">Password</label>
  <input id="password" type="password" placeholder="Password" />
</form>
Enter fullscreen mode Exit fullscreen mode
input[type="text"] {
  color: chocolate;
}
Enter fullscreen mode Exit fullscreen mode

这会将巧克力色文本颜色应用于每个<input>具有文本type精确值的属性的元素

输出:

替代文本


我们也可以使用此语法来模拟 ID 选择器(记住第 4 节中的示例):

[id="users-table"] {
  background-color: black;
  color: white;
}

[id="staff-table"] {
  border: 1px solid black;
}
Enter fullscreen mode Exit fullscreen mode

说明:通过使用此属性选择器语法,我们定位到包含id属性且其值恰好为users-tablestaff-table 的元素。我们使用此语法是因为一个元素只能有一个idname,因此该值必须精确 (=)。

语法 3

[attr~=value] { 样式属性 }

匹配attr值为空格分隔的单词列表且其中一个单词正好为 value 的元素。

<p lang="en-gb en-us en-ca en-au en-nz">Welcome!</p>
<p lang="fr-fr fr-ca fr-be">Bienvenue!</p>
Enter fullscreen mode Exit fullscreen mode
p[lang~="en-us"] {
  color: navy;
}
p[lang~="fr-fr"] {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

这会将深蓝色应用于<p>的值包含精确字符串en-us 的lang列表的每个元素。对于 的包含fr-fr的所有元素也是如此,在本例中应用红色。<p>lang

输出:

替代文本


除了前面的语法(我们可以用它来模拟 ID 选择器的行为)之外,我们还可以使用这个属性语法来模拟类选择器的行为

[class~="list-item"]{
  padding: 5px;
}
Enter fullscreen mode Exit fullscreen mode

说明:通过使用此属性选择器语法,我们定位具有类属性的元素,该类属性的值是包含字符串list-item的列表

我们使用这种特定的语法,是因为一个元素可以包含多个类,而我们只想使用其中一个 (~=)。即使元素只有一个类,class 属性的值也始终表现得像一个值列表

语法 4

[attr|=value] { 样式属性 }

匹配attr的值正好是 value 或以 value 开头后跟连字符 的元素

<p lang="en-us">Hello</p>
<p lang="en-gb">Hello</p>
Enter fullscreen mode Exit fullscreen mode
p[lang|="en"] {
  background-color: cornflowerblue;
  color: antiquewhite;
}
Enter fullscreen mode Exit fullscreen mode

这会将矢车菊蓝色背景颜色和古董白色文本颜色应用于每个<p>具有lang属性值恰好为en或以en-开头的元素。

输出:

替代文本

语法 5

[attr^=value] { 样式属性 }

匹配attr值以 value开头的元素。

<a href="#list1">Go to list 1</a>
<a href="#list2">Go to list 2</a>
<section>
  <h1>Lists</h1>
  <div id="list1">
    <h1>List 1</h1>
    <ul>
      <li>Milk</li>
      <li>Butter</li>
      <li>Eggs</li>
      <li>Sugar</li>
    </ul>
  </div>
  <div id="list2">
    <h1>List 2</h1>
    <ul>
      <li>Oranges</li>
      <li>Lemons</li>
      <li>Strawberries</li>
      <li>Apples</li>
    </ul>
  </div>
</section>
Enter fullscreen mode Exit fullscreen mode
a[href^="#"] {
  color: crimson;
  font-size: 2rem;
}
Enter fullscreen mode Exit fullscreen mode

这会将深红色和 2rem 的字体大小应用于每个<a>具有以#href开头的属性的元素输出:

替代文本

语法 6

[attr$=value] { 样式属性 }

匹配attr值以 value结尾的元素

<a href="css-selectors-guide.pdf">CSS Selectors Guide</a>
Enter fullscreen mode Exit fullscreen mode
a[href$=".pdf"] {
  color: slateblue;
}
Enter fullscreen mode Exit fullscreen mode

<a>这将为每个具有以.pdfhref结尾的属性的元素应用灰蓝色输出:

替代文本

语法 7

[attr*=value] { 样式属性 }

匹配attr的值至少包含一次 value的元素。

<div class="small-box">
  <p>This is a small box</p>
</div>
<div class="big-box">
  <p>This is a big box</p>
</div>

Enter fullscreen mode Exit fullscreen mode
div[class*="box"] {
  background-color: burlywood;
}
Enter fullscreen mode Exit fullscreen mode

这将对包含属性(其值至少出现一次字符串box )的每个<div>元素应用一种棕褐色背景颜色class

输出:

替代文本

分组选择器

CSS 中的分组选择器基本上用于将我们想要应用相同样式属性的不同类型或不同 id/类的元素放在一起

此外,通过使用这种技术,我们将摆脱冗余,我们的代码将变得干净简洁有条理

组选择器

语法: elem1,...,elemN {样式属性}

该选择器用逗号(,)表示,匹配列表中所述的所有元素并对所有元素应用相同的规则集。

<h1>Computer Science Engineering</h1>
<h2>List of courses</h2>
<ul>
  <li>Algebra</li>
  <li>Calculus</li>
  <li>Physics</li>
  <li>Discrete Mathematics</li>
  <li>Introduction to Programming</li>
</ul>

Enter fullscreen mode Exit fullscreen mode
h1, h2, li {
  color: darkred;
}
Enter fullscreen mode Exit fullscreen mode

<h1>这将为每个、<h2><li>元素应用深红色。

输出:
替代文本

组合选择器

CSS 选择器也可以组合。通过组合选择器,我们可以定义CSS 组合器

CSS 组合器用于建立不同选择器之间的关系,对于使元素选择更有针对性非常有用。

1. 后代组合器

语法: elem1 elem2 { 样式属性 }

该组合器由一个空格( )表示,并匹配elem1的所有后代elem2

考虑以下导航:

<nav>
  <ul>
    <li><a>Home</a></li>
    <li>
      <a>People</a>
      <ul>
        <li><a>Students</a></li>
        <li>
          <a>Faculty members</a>
          <ul>
            <a>Discrete Mathematics</a>
            <a>Programming</a>
            <a>Physics</a>
            <a>Algorithms</a>
          </ul>
        </li>
        <li><a>Staff members</a></li>
      </ul>
    </li>
    <li><a>About</a></li>
    <li><a>Contact</a></li>
  </ul>
</nav>
Enter fullscreen mode Exit fullscreen mode
nav a {
  border: 1px solid crimson;
  color: darkslateblue;
  font-size: 1.5rem;
  font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

<a>这将对元素的每个后代元素应用 1px 实心深红色边框、深石板蓝色、1.5rem 的字体大小和粗体字体粗细<nav>无论它们如何嵌套

输出:

替代文本

2. 子组合器

语法: elem1 > elem2 { 样式属性 }

该组合器由提示符(>)表示,并匹配elem1的所有直接子元素elem2

<div class="box">
  <p>This is a direct child of .box</p>
  <div>
    <p>This is not a direct child of .box</p>
  </div>
  <p>This is another direct child of .box</p>
</div>
Enter fullscreen mode Exit fullscreen mode
.box > p {
  color: darkgoldenrod;
}
Enter fullscreen mode Exit fullscreen mode

这会将深金色应用于<p>具有类box的任何元素的直接子元素,因此,在此 HTML 示例中,将选择第一个和最后一个<p>元素,但不会选择中间的元素。

输出:

替代文本

3. 通用兄弟组合器

语法: elem1 ~ elem2 { 样式属性 }

该组合器用波浪号(~)表示,它匹配所有与 elem1 同级且在 elem1 之后的elem2

<img src="blue-mug.jpeg" alt="a regular blue coffee mug" />
<p>Blue mug</p>
<p>Price: $15</p>
Enter fullscreen mode Exit fullscreen mode
img ~ p {
  color: darkblue;
}
Enter fullscreen mode Exit fullscreen mode

这会将深蓝色应用于任何元素之后<p>的所有同级元素。在本例中,两个元素都将被选中。<img><p>

输出:
替代文本

4. 相邻兄弟组合器

语法: elem1 + elem2 { 样式属性 }

该组合器用加号 (+)表示,它匹配所有与 elem1 同级且紧随其后出现的elem2

<img src="blue-mug.jpeg" alt="a regular blue coffee mug" />
<p>Blue mug</p>
<p>Price: $15</p>
Enter fullscreen mode Exit fullscreen mode
img + p {
  color: darkblue;
}
Enter fullscreen mode Exit fullscreen mode

在这种情况下,只会选择第一个<p>元素,因为第二个元素不会紧接着该<img>元素出现。

输出:
替代文本

伪类

CSS 伪类是添加到选择器的关键字,定义所选元素的特殊状态。

语法: elem:pseudo-class { 样式属性 }

该选择器用冒号(:)表示。

<h1>Shopping list</h1>
<ul>
  <li>Milk</li>
  <li>Butter</li>
  <li>Eggs</li>
  <li>Sugar</li>
</ul>
Enter fullscreen mode Exit fullscreen mode
li:hover {
  background-color: black;
  color: white;
}
Enter fullscreen mode Exit fullscreen mode

<li>在这个例子中,当光标悬停在每个元素上时,我们对其应用黑色背景颜色和白色文本颜色。

看看当我们将鼠标悬停在Butter元素上时会发生什么:

输出:
替代文本

一些最常见的 CSS 伪类是:

:active,,,,,,,,:hover:focus:disabled:checked:first-child:nth-child:first-of-type

伪元素

CSS 伪元素是添加到选择器以设置所选元素特定部分的样式的关键字。

语法: elem:pseudo-element { 样式属性 }

该选择器由双冒号(::)表示。

<p>CODE</p>
Enter fullscreen mode Exit fullscreen mode
p::before{
  content: "_";
}
Enter fullscreen mode Exit fullscreen mode

<p>在这个例子中,我们在每个元素前面附加一个下划线符号。

输出:
替代文本

一些最常见的 CSS 伪元素是:

::after也可以写成:after),::before(也可以写成:before::marker,,,,::placeholder::first-letter


差不多就是这样了 🙂

我希望本参考指南对您有所帮助。

您还可以在@underscorecode Instagram 帐户上查看有关 CSS 选择器的以下相关文章


🎉 不要忘记InstagramTwitter上关注@underscorecode,获取更多每日 webdev 内容 🖥🖤

文章来源:https://dev.to/underscorecode/css-selectors-the-full-reference-guide-3cbf
PREV
样式化组件 101 💅 讲座 2:创建主题 + 明暗主题切换器示例 ☀️🌙 创建主题文件 🔮 使主题文件可通过应用程序访问 🕵️ 在样式化组件中使用主题 💅 在自定义 React 组件中使用主题 ⚛️ 主题 prop 🤖 使用 JavaScript 对象编写样式而不是 CSS 🤹‍♀️ 现在... 👑 皇冠上的宝石:让我们使用样式化组件创建一个明暗主题切换器 结果 ☀️ ➡️ 🌙
NEXT
无需 create-react-app 从头创建您的 React 项目:完整指南。