选择器(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",
    "Helvetica",
    "Arial",
    sans-serif;
}

这里的选择器有 "p"(它将任何 <p> 元素内的文本颜色设为绿色)、"div.warning"(它使任何带有 class "warning"<div> 元素看起来像一个警告框),以及 "#customized"(它将 ID 为 "customized" 的元素的基础字体设置为 16 像素高的 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>

生成的页面内容样式如下

另见