---
title: "第2章 选择器  =>类选择器 P39"
author: "conkeyn"
date: "2009-04-26T11:39:25Z"
tags: ["CSS", "HTML", "XHTML", "工作"]
slug: "2-p39"
draft: false
lastmod: "2009-04-26T11:46:29Z"
id: 375014
url: "https://conkeyn.iteye.com/blog/375014"
---

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>类选择器</title>
<style type="text/css">
*.warning{
	font-weight:bold;}
</style>
</head>

<body>
<p class="warning">When handling plutonium,care must be taken to avoid the formation of a critaical mass.</p>
<p>
With plutonium, <span class="warning">the possibility of important is very real,and must be avoided at all costs</span>. This can be accomplished by keeping the various mass separate.</p>
</body>
</html>
```

 显示效果：

 

![](/upload/attachment/97896/ac3aca03-1b17-37f6-9c34-61a64f2f9c5d.bmp)

 

为了将一个类选择器的样式与元素关联，必段将class属笥指定为一个适当的值。在前面的代码中，有两个元素的class值指定为warning；第一段（第一个p元素）以及第二段中的span元素。

 

类选择器要正常工作，需要直接引用一个元素的class属笥中的值。这个引用前面往往有一个点号（.），标记这是一个类选择器。通过这个点号，可以帮助类选择器与它可能结合的其他部分分隔开（如类选择器可能结合了元素选择器）。

 

例如：可能希望只在整个段落是警告时才显示为粗体文本：

p.warning{font-weight:blod;}

 

选择器现在会匹配class属笥包含warning的所有p元素，但是其他任何类型的元素都不能匹配，不论是否有此class属性。

选择器p.warning解释为“其class属性包含词为warning的所有段落(p元素)。”因为span元素不是一个p元不经，这个规则的选择器与之不匹配，不能变为粗体文本。