翻译源http://www.w3schools.com/css/css_id_class.asp
CSS Id和Class
id和class也可以用作选择器
在“CSS语法”中提到,设置样式时,用HTML元素作为选择器,
还可以使用自定义选择器,即“id”,“class”
id选择器
给单一的,独特的元素指定样式时,使用id选择器。
id选择器使用HTML元素的id属性,用“#”定义。
下面的样式将被应用到id =“para1”的元素:
#para1
{
text-align:center;
color:red;
}
例子
class选择器
给一个组元素指定样式时,使用class选择器。
与id选择器不同,class选择器最常用于指定多个元素的样式。
可以使用一个class选择器,对多个HTML元素,设置一个特定的样式。
class选择器使用HTML元素的class属性,用“.”定义。
在下面的示例中,所有的HTML元素使用 class="center"样式,居中样式:
.center {text-align:center;}
例子
您还可以特指只有特定的HTML元素使用该class选择器样式。
在下面的示例中,所有p元素class=“center”,居中方式:
p.center {text-align:center;}
例子
注意:不要以数字开头命名class, 仅仅Internet Explorer支持以数字开头的class命名方式。
CSS Id和Class
id和class也可以用作选择器
在“CSS语法”中提到,设置样式时,用HTML元素作为选择器,
还可以使用自定义选择器,即“id”,“class”
id选择器
给单一的,独特的元素指定样式时,使用id选择器。
id选择器使用HTML元素的id属性,用“#”定义。
下面的样式将被应用到id =“para1”的元素:
#para1
{
text-align:center;
color:red;
}
例子
<!DOCTYPE html>
<html>
<head>
<style>
#para1
{
text-align:center;
color:red;
}
</style>
</head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style.</p>
</body>
</html>
注意:不要以数字开头命名ID,Mozilla/Firefox不支持以数字开头的ID命名方式。
class选择器
给一个组元素指定样式时,使用class选择器。
与id选择器不同,class选择器最常用于指定多个元素的样式。
可以使用一个class选择器,对多个HTML元素,设置一个特定的样式。
class选择器使用HTML元素的class属性,用“.”定义。
在下面的示例中,所有的HTML元素使用 class="center"样式,居中样式:
.center {text-align:center;}
例子
<!DOCTYPE html>
<html>
<head>
<style>
.center
{
text-align:center;
}
</style>
</head>
<body>
<h1 class="center">Center-aligned heading</h1>
<p class="center">Center-aligned paragraph.</p>
</body>
</html>
您还可以特指只有特定的HTML元素使用该class选择器样式。
在下面的示例中,所有p元素class=“center”,居中方式:
p.center {text-align:center;}
例子
<!DOCTYPE html>
<html>
<head>
<style>
.center
{
text-align:center;
}
</style>
</head>
<body>
<h1 class="center">Center-aligned heading</h1>
<p class="center">Center-aligned paragraph.</p>
</body>
</html>
注意:不要以数字开头命名class, 仅仅Internet Explorer支持以数字开头的class命名方式。