目录
一、元素选择器
二、id选择器(# id)
三、类选择器(. class)
四、属性选择器
一、元素选择器
选择器通常将是某个 HTML 元素,比如 p、h1、em、a,甚至可以是 html 本身:
html {color:black;}
h1 {color:blue;}
h2 {color:silver;}
二、id选择器(# id)
id 选择器以 "#" 来定义。
示例:下面两个 id 选择器,第一个可以定义元素的颜色为红色,第二个定义元素的颜色为绿色
#red {color:red;}
#green {color:green;}
下面的 HTML 代码中,id 属性为 red 的 p 元素显示为红色,而 id 属性为 green 的 p 元素显示为绿色。
<p id="red">这个段落是红色。</p>
<p id="green">这个段落是绿色。</p>
注意:id 属性只能在每个 HTML 文档中出现一次。
三、类选择器(. class)
类选择器以一个点号显示:
示例:定义拥有 center 类的 HTML 元素均为居中。
.center {text-align: center}
在下面的 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>
补充1:元素也可以基于它们的类而被选择
td.fancy {
color: blue;
background: green;
}
在上面的例子中,类名为 fancy 的表格单元将是带有绿色背景的蓝色。
<td class="fancy">
可以将类 fancy 分配给任何一个表格元素任意多的次数。(这点与id选择器不同)
补充2:CSS 多类选择器
在 HTML 中,一个 class 值中可能包含多个词,各个词之间用空格分隔。
.important {font-weight:bold;} //加粗
.warning {font-style:italic;} //斜体
.important.warning {background:silver;} //背景色
<p class="important">This paragraph is very important.</p>
<p class="warning">This is a warning.</p>
<p class="important warning">This paragraph is a very important warning.</p>
效果如下:

四、属性选择器
对带有指定属性的 HTML 元素设置样式,不仅限于 class 和 id 属性。
(1) 属性选择器
示例:为带有 title 属性的所有元素设置样式:
[title] { color:red; }
<h2 title="Hello world">Hello world</h2>
(2) 属性和值选择器
[title=Hello] {border:5px solid blue;}
<h2 title="Hello>Hello world</h2>
(3) 属性和值选择器 - 多个值
下面的例子为包含指定值的 title 属性的所有元素设置样式。适用于由空格分隔的属性值:
[title~=hello] { color:red; }
<h2 title="hello world">Hello world</h2>
下面的例子为带有包含指定值的 lang 属性的所有元素设置样式。适用于由连字符分隔的属性值:
[lang|=en] { color:red; }
<p >Hi!</p>
(4) 设置表单的样式
属性选择器在为不带有 class 或 id 的表单设置样式时特别有用:
input[type="text"]
{
width:150px;
background-color:yellow;
}
input[type="button"]
{
width:120px;
margin-left:35px;
}
<input type="text" name="Name" value="Gates" size="20">
<input type="button" value="Example Button">