为什么要用选择器?
要使用CSS对HTML页面中的元素实现一对一,一对多或者多对一的控制,这就需要用到CSS选择器。
Id选择器
id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式。
HTML元素以id属性来设置id选择器,CSS 中 id 选择器以 "#" 来定义。
ID属性不要以数字开头,数字开头的ID在 Mozilla/Firefox 浏览器中不起作用。
举例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#h1id{
color: yellowgreen;
}
#h1id2{
color: aqua;
}
</style>
</head>
<body>
<h1 id="h1id">我是h1标签</h1>
<h1 id="h1id2">我是h1标签2</h1>
</body>
</html>
效果展示
![](https://img-blog.csdnimg.cn/img_convert/dbc050ed7aca9811b781b26f3ed9af7a.png)
4.class选择器
class 选择器用于描述一组元素的样式,class 选择器有别于id选择器,class可以在多个元素中使用。
class 选择器在 HTML 中以 class 属性表示, 在 CSS 中,类选择器以一个点 . 号显示:
5.举例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 类型一:所有属于lie的类颜色都为粉色 -->
<style>
.lei{
color: violet;
}
</style>
<!-- 类型二:选择某一标签的类,只影响被选择标签这类 -->
<style>
p.lei{
text-align: center;
}
</style>
<!-- 类型三:多个选择器可以分开选择 -->
<style>
.lei{
background-color: tomato;
}
.color{
color: aliceblue;
}
</style>
</head>
<body>
<!-- class类选择器 -->
<h1 class="lei">我是类选择器实验对象</h1>
<p class="lei">我也是类选择器实验对象</p>
<p class="lei color">对比1</p>
</body>
</html>
6.效果
![](https://img-blog.csdnimg.cn/img_convert/63c3b51fca7860e48b7c82cc0849e2af.png)