---
title: "CSS样式"
author: "tory320"
date: "2009-02-24T15:47:38Z"
tags: []
slug: "css"
draft: false
lastmod: "2009-02-24T15:47:38Z"
id: 338008
url: "https://tory320.iteye.com/blog/338008"
---

## id 选择器和派生选择器

**在现代布局中，id 选择器常常用于建立派生选择器。**

```
#sidebar p
 {
	font-style: italic;
	text-align: right;
	margin-top: 0.5em;
	}
```

上面的样式只会应用于出现在 id 是 sidebar 的元素内的段落。这个元素很可能是 div 或者是表格单元，尽管它也可能是一个表格或者其他块级元素。它甚至可以是一个内联元素，比如 &lt;em&gt;&lt;/em&gt; 或者 &lt;span&gt;&lt;/span&gt;，不过这样的用法是非法的，因为不可以在内联元素 &lt;span&gt; 中嵌入 &lt;p&gt; （如果你忘记了原因，请参阅 [XHTML:网站重构](http://www.w3school.com.cn/xhtml/xhtml_structural_01.asp) ）。

### 一个选择器，多种用法

**即使被标注为 sidebar 的元素只能在文档中出现一次，这个 id 选择器作为派生选择器也可以被使用很多次：**

```
#sidebar p
 {
	font-style: italic;
	text-align: right;
	margin-top: 0.5em;
	}

#sidebar h2
 {
	font-size: 1em;
	font-weight: normal;
	font-style: italic;
	margin: 0;
	line-height: 1.5;
	text-align: right;
	}
```

在这里，与页面中的其他 p 元素明显不同的是，sidebar 内的 p 元素得到了特殊的处理，同时，与页面中其他所有 h2 元素明显不同的是，sidebar 中的 h2 元素也得到了不同的特殊处理。

## 单独的选择器

**id 选择器即使不被用来创建派生选择器，它也可以独立发挥作用：**

```
#sidebar
 {
	border: 1px dotted #000;
	padding: 10px;
	}
```

根据这条规则，id 为 sidebar 的元素将拥有一个像素宽的黑色点状边框，同时其周围会有 10 个像素宽的内边距（padding，内部空白）。老版本的 Windows/IE 浏览器可能会忽略这条规则，除非你特别地定义这个选择器所属的元素：

```
div#sidebar
 {
	border: 1px dotted #000;
	padding: 10px;
	}
```

 

 

**在 CSS 中，类选择器以一个点号显示：**

```
.center
 {text-align: center}
```

在上面的例子中，所有拥有 center 类的 HTML 元素均为居中。

在下面的 HTML 代码中，h1 和 p 元素都有 center 类。这意味着两者都将遵守 ".center" 选择器中的规则。

```
<h1 class="center"
>
This heading will be center-aligned
</h1>

<p class="center"
>
This paragraph will also be center-aligned.
</p>
```

注意： 类名的第一个字符不能使用数字！它无法在 Mozilla 或 Firefox 中起作用。

 

**和 id 一样，class 也可被用作派生选择器：**

```
.fancy td
 {
	color: #f60;
	background: #666;
	}
```

在上面这个例子中，类名为 fancy 的更大的元素内部的表格单元都会以灰色背景显示橙色文字。（名为 fancy 的更大的元素可能是一个表格或者一个 div）

**元素也可以基于它们的类而被选择：**

```
td.fancy
 {
	color: #f60;
	background: #666;
	}
```

在上面的例子中，类名为 fancy 的表格单元将是带有灰色背景的橙色。

```
<td class="fancy"
>
```