--- title: Selector (CSS) slug: Glossary/CSS_Selector tags: - CSS - CSS 选择器 - Glossary - HTML - 选择器 translation_of: Glossary/CSS_Selector ---

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, Arial, Halvetica等 无衬线字体。)

我们可以把上面的 css 添加给 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>

页面的内容将会呈现如下风格:

{{EmbedLiveSample("glossary-selector-details", 640, 210)}}