使用逗號 , 分隔多個選擇器,套用相同樣式規則:
selector1, selector2, selector3 {
/* 共同樣式 */
}
注意:逗號必須為半形(英文模式),全形逗號無效。
h1, h2, h3, h4, h5, h6,
p, span, .text-content {
font-size: 12px;
color: #FF0000;
font-family: Arial, sans-serif;
}
以上 9 個選擇器共用同一組字體設定,避免重複撰寫 9 次。
/ * 易讀 * /
h1,
h2,
h3 { color: red; }
/ * 難讀 * /
h1,h2,h3{color:red;}
每個選擇器獨立匹配,不是交集。若需「同時擁有 A 和 B」,請鏈式寫法:.a.b { }。
/ * 危險:連標題、段落、按鈕都強制同樣字體 * /
h1, h2, p, button, input { font-family: Arial; }
/ * 建議:分組按語意 * /
/* 文字內容共用 */
.article-title, .article-body, .comment-text { font-family: "Noto Sans TC", sans-serif; }
/* 表單控制項共用 */
input, button, select, textarea { font-family: inherit; }
:root {
--text-base-size: 1rem;
--text-primary-color: #333;
--font-family-base: "Noto Sans TC", sans-serif;
}
h1, h2, .title { font-size: calc(var(--text-base-size) * 2); color: var(--text-primary-color); font-family: var(--font-family-base); }
p, .desc { font-size: var(--text-base-size); color: var(--text-primary-color); font-family: var(--font-family-base); }
群組選擇器是減少重複代碼的基礎技巧,配合語意化分組與 CSS 變數,能建立可擴展、易維護的樣式系統。