萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 群組選擇器(逗號)語法與最佳實踐

定義

群組選擇器以**逗號**分隔多個選擇器,**共享同一組樣式宣告**,減少重複程式碼。

語法與範例

h1, h2, h3, h4, h5, h6,
p, span, .text-content {
  font-family: Arial, sans-serif;
  font-size: 12px;
  color: #FF0000;
}

關鍵細節

  • 逗號**必須為半形**(英文輸入模式),全形逗號會導致解析錯誤
  • 每個選擇器獨立匹配,**無關聯性**
  • 可混合不同類型選擇器(標籤、class、id、屬性、偽類等)

實務優化技巧

提取共同基礎樣式

/* 基礎排版 */
.body-text, .caption, .footnote {
  line-height: 1.6;
  color: #333;
}

/* 各自差異 */
.body-text { font-size: 1rem; }
.caption { font-size: 0.875rem; font-style: italic; }
.footnote { font-size: 0.75rem; opacity: 0.7; }

搭配 CSS 變數(自訂屬性)

:root {
  --text-base: 1rem;
  --text-sm: 0.875rem;
}

.text-lg, .text-md, .text-sm {
  font-family: var(--font-family);
  color: var(--text-color);
}
.text-lg { font-size: calc(var(--text-base) * 1.25); }
.text-md { font-size: var(--text-base); }
.text-sm { font-size: var(--text-sm); }

常見錯誤

/* 錯誤:全形逗號 */
h1,h2 { color: red; }

/* 錯誤:最後一個選擇器後多加逗號 */
h1, h2, { color: red; }

總結

群組選擇器是**減少 CSS 體積、提升可維護性**的基礎技巧。善用它提取共同樣式,再配合變數與模組化架構,能構建乾淨、可擴展的樣式系統。

copyright © 萬盛學電腦網 all rights reserved