CSS之id和class选择器

在HTML元素中使用CSS样式表,需要在元素中设置"id" 和 “class” 属性

id 选择器

  • id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式。
  • HTML元素以id属性来设置id选择器,CSS 中 id 选择器以 “#” 来定义
  • ID属性不要以数字开头,数字开头的ID在 Mozilla/Firefox 浏览器中不起作用
  • D属性只能在每个 HTML 文档中出现一次

代码示例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<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>

class 选择器

  • class 选择器用于描述一组元素的样式,可以在多个元素中使用
  • class 选择器在HTML中以class属性表示, 在 CSS 中,类选择器以一个点"."号显示
  • 可以为特定的HTML元素的class制定样式

代码示例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<style>
.center
{
	text-align:center;
}
p.center
{
    text-align:right;
}
</style>
</head>

<body>
<h1 class="center">标题1居中</h1>
<h2 class="center">标题2居中</h2> 
<p class="center">段落居中,在css中改为居右</p> 
</body>
</html>
发布了28 篇原创文章 · 获赞 22 · 访问量 770

猜你喜欢

转载自blog.csdn.net/devin_xin/article/details/105027974
今日推荐