類選擇器

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

CSS 類選擇器根據元素的 class 屬性的內容來匹配元素。

css
/* All elements with class="spacious" */
.spacious {
  margin: 2em;
}

/* All <li> elements with class="spacious" */
li.spacious {
  margin: 2em;
}

/* All <li> elements with a class list that includes both "spacious" and "elegant" */
/* For example, class="elegant retro spacious" */
li.spacious.elegant {
  margin: 2em;
}

語法

css
.class_name {
  /* … */
}

請注意,這等同於以下屬性選擇器

css
[class~="class_name"] {
  /* … */
}

class_name 值必須是有效的 CSS 識別符號。並非有效 CSS 識別符號的 HTML class 屬性在使用類選擇器之前必須進行轉義

示例

有效類選擇器

HTML

html
<p class="red">This paragraph has red text.</p>
<p class="red yellow-bg">
  This paragraph has red text and a yellow background.
</p>
<p class="red fancy">This paragraph has red text and "fancy" styling.</p>
<p>This is just a regular paragraph.</p>
html
<!-- The next two paragraphs have class attributes
that contain characters which must be escaped in CSS -->

<p class="item?one">This paragraph has a pink background.</p>
<p class="123item">This paragraph has a yellow background.</p>

CSS

css
.red {
  color: #ff3333;
}

.yellow-bg {
  background: #ffffaa;
}

.fancy {
  font-weight: bold;
  text-shadow: 4px 4px 3px #7777ff;
}
css
/* In the next two rules, the class attributes must be escaped */

.item\?one {
  background-color: pink;
}

.\00003123item {
  background-color: yellow;
}

結果

無效類選擇器

以下規則中的類選擇器不是有效的 CSS 識別符號,將被忽略。

css
.item?one {
  background-color: green;
}

.123item {
  background-color: green;
}

規範

規範
選擇器 Level 4
# class-html

瀏覽器相容性

另見