CSS 分组和嵌套选择器 - 优化样式规则

最后编辑于2025-04-14 12:03:14.600342 +0800 CST

CSS 分组和嵌套

分组选择器

在样式表中有很多具有相同样式的元素。

css
1h1 {
2    color: green;
3}
4h2 {
5    color: green;
6}
7p {
8    color: green;
9}

为了尽量减少代码,你可以使用分组选择器。

每个选择器用逗号分隔。

在下面的例子中,我们对以上代码使用分组选择器:

css
1h1, h2, p {
2    color: green;
3}

提示:分组选择器大大减少了代码量,提高了样式表的可维护性。


嵌套选择器

嵌套选择器允许你为选择器内部的选择器定义样式。

在下面的例子设置了四种不同的选择器样式:

  • p { }: 为所有 p 元素指定一个样式。
  • .marked { }: 为所有 class=“marked” 的元素指定一个样式。
  • .marked p { }: 为所有 class=“marked” 元素内的 p 元素指定一个样式。
  • p.marked { }: 为所有 class=“marked” 的 p 元素指定一个样式。
css
 1p {
 2    color: blue;
 3    text-align: center;
 4}
 5.marked {
 6    background-color: red;
 7}
 8.marked p {
 9    color: white;
10}
11p.marked {
12    text-decoration: underline;
13}

嵌套选择器的使用场景

嵌套选择器在创建具有层次结构的样式时特别有用。以下是一些常见场景:

  1. 导航菜单样式
css
 1nav {
 2    background-color: #333;
 3}
 4nav ul {
 5    list-style-type: none;
 6    margin: 0;
 7    padding: 0;
 8}
 9nav ul li {
10    display: inline-block;
11}
12nav ul li a {
13    color: white;
14    text-decoration: none;
15    padding: 10px 15px;
16}
  1. 文章内容格式化
css
 1article {
 2    font-family: Arial, sans-serif;
 3}
 4article h2 {
 5    color: #4a4a4a;
 6    border-bottom: 1px solid #eaeaea;
 7}
 8article p {
 9    line-height: 1.6;
10}
11article ul li {
12    margin-bottom: 5px;
13}

通过合理使用分组和嵌套选择器,可以使你的CSS代码更加简洁、有组织性,并且更易于维护。