CSS 中的分组选择器


CSS 分组选择器用于选择多个元素并为它们设定共同的样式。这可以减少代码量,避免为每个元素分别声明通用样式;若要对选择器进行分组,每个选择器之间都应使用空格分隔。

本文将介绍如何在 CSS 中应用分组选择器。

在 CSS 中应用分组选择器

我们使用了元素名称和元素 ID 应用了分组选择器。

  • 我们使用了 divarticle 作为分组选择器,使用 background-colorcolortext-align 属性对 div 和 article 标记进行设置,使其居中对齐,具有绿色的背景和白色的文字颜色。
  • 我们还使用了 id1 和 id2 ID 选择器,作为分组选择器,对 h4 和 span 元素应用了 paddingborder

示例

以下是实现上述步骤以应用分组选择器的完整示例代码。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Grouping Selector in CSS</title>
    <style>
        div, article {
            background-color: #04af2f;
            color: white;
            text-align: center;
            font-size: 20px;
        }
        #id1, #id2 {
            padding: 5px;
            border: 2px solid black;
        }
    </style>
</head>
<body>
    <h2>
        Grouping Selector in CSS
    </h2>
    <p><strong>
            In this example, both div and article
            element have same background-color, text
            color and aligned to center using
            grouping selector.
        </strong></p>
    <div>
        This is a div element
    </div>
    <br>
    <article>
        This is an article element.
    </article>
    <p><strong>
            In this example, both h4 and span
            element have same padding, and
            border properties using grouping
            selector.
        </strong></p>
    <h4 id="id1">
        This h4 element has padding and border
        properties.
    </h4>
    <span id="id2">
        This span element also has padding and
        border properties.
    </span>
</body>
</html>

您可以参考我们的 CSS 选择器 教程了解更多信息。

结论

在本文中,我们已经了解了在 CSS 中应用分组选择器是一项简单的任务。我们已经使用元素和 ID 来应用分组选择器并设计 HTML 结构。

更新于: 14-8-2024

1.6 万次浏览

开启您的 职业生涯

完成课程取得认证

开始
广告
© . All rights reserved.