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.