日期:2014-05-16  浏览次数:20573 次

CSS 类选择器

1、在 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>

?

2、类选择器可以结合元素选择器来使用
例如,

p.important {color:red;}

?
选择器会匹配 class 属性包含 important 的所有 p 元素,但是其他任何类型的元素都不匹配,不论是否有此 class 属性。选择器 p.important 解释为:“class 属性值为 important 的所有段落”。

?

3、一个 class 值中可能包含一个词列表,各个词之间用空格分隔。例如,如果希望将一个特定的元素同时标记为重要(important)和警告(warning),就可以写作:

<p class="important warning">
This paragraph is a very important warning.
</p>

?
这两个词的顺序无关紧要,写成 warning important 也可以。

我们假设 class 为 important 的所有元素都是粗体,而 class 为 warning 的所有元素为斜体,class 中同时包含 important 和 warning 的所有元素还有一个银色的背景 。就可以写作:

.important {font-weight:bold;}
.warning {font-style:italic;}
.important.warning {background:silver;}

?

4、class 也可被用作派生选择器

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

?在上面这个例子中,class属性值为 fancy 的元素,其内部的表格单元都会以灰色背景显示橙色文字。(名为 fancy 的元素可能是一个表格或者一个 div)


?