CSS(二) Id和Class选择器

如果你要在HTML元素中设置CSS样式,你需要在元素中设置“id”和“class”选择器。

1.id选择器

  • id选择器可以为标有特定id的html元素指定特定的样式。
  • html元素以id属性来设置id选择器,css中id选择器以“#”来定义。

以下的样式规则应用于元素属性id=“para1”:

<html>
<head>
<meta charset="utf-8"/>
<title>css实例</title>
<style>
#para1{
text-align:center;
color:red;
}
</style>
</head>
<body>
<p id="para1">hello  world</p>
</body>
</html>
  • 注意:id属性不要以数字开头,数字开头的ID在Mozilla、Firefox浏览器中不起作用。
  • id属性只能在每个HTML文档中出现一次。

2.class选择器

class选择器用于描述一组元素的样式,class选择器有别于id选择器,class可以在多个元素中使用

class选择器在html中以class属性表示,在CSS中,类选择器以一个点“.”号表示:

在以下的例子中,所有拥有center类的html元素均为居中。

实例:

<html>
<head>
<meta charset="utf-8"/>
<title>css实例</title>
<style>
.center{
text-align:center;
}
</style>
</head>
<body>
<h1  class="center">标题居中</h1>
<p class="center">标题居中</p>
</body>
</html>
  • 你也可以指定特定的html元素使用class。

  • 在下面实例中,所有的p元素使用class="center"让该元素的文本居中:

  • <html>
    <head> 
    <meta  charset="utf-8"/>
    <style>
    p.center{
    color:red;
    text-align:center;
    }
    </style>
    </head>
    <body>
    <h1 class="center">hello world</h1>       //没有居中,字体没有变红
    <p class="center">hello  world</p>     //居中且字体变红
    </body>
    </html>

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

  •  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值