CSS Id和Class

翻译源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;
}
例子
<!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命名方式。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值