CSS 选择器

CSS 选择器是 CSS 规则的一部分,用于匹配文档中的元素。匹配的元素将会应用规则指定的样式。

示例

看下面的 CSS:

css
p {
  color: green;
}

div.warning {
  width: 100%;
  border: 2px solid yellow;
  color: white;
  background-color: darkred;
  padding: 0.8em 0.8em 0.6em;
}

#customized {
  font:
    16px Lucida Grande,
    Arial,
    Helvetica,
    sans-serif;
}

选择器例如:"p"(文档中的 <p> 元素都会应用绿色字体的样式)、"div.warning"(文档中所有 class 包含 "warning"<div> 元素都会有一个看起来像警告框的样式)和 "#customized"(id 为 "customized" 的元素中的文本为 16px 高,字体是 Lucida Grande 和一些用作回落的字体)。

我们可以把上面的 CSS 应用到 HTML 中,如下:

html
<p>This is happy text.</p>

<div class="warning">
  Be careful! There are wizards present, and they are quick to anger!
</div>

<div id="customized">
  <p>This is happy text.</p>

  <div class="warning">
    Be careful! There are wizards present, and they are quick to anger!
  </div>
</div>

页面的内容将会呈现如下样式:

参见