CSS的能力,就是通过选择器选择到对应的某些/某个元素,然后设置属性,改变他们的样式。
如何才能选择到我们的元素呢?
选择器 {
属性: 属性值;
属性: 属性值;
}
1. 标签选择器
当我们在CSS中想要给某类标签上添加样式时,就可以使用标签选择器
标签名 {
}
标签选择器直接使用对应的标签名即可。
<!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>
p {
color: red;
}
</style>
</head>
<body>
<p>文字</p>
<div>文字</div>
<span>文字</span>
<p>文字</p>
</body>
</html>
2. 类选择器
类选择器就像是我们的姓名一样,是后期由父母赋予我们的,类是由开发者赋予给标签的。
2.1. 怎么样才能给我们的标签添加类名呢?
所有的标签都有一个属性,叫class。这个属性的值需要我们按照规则自定义。
<标签名 class="类名"></标签名>
类名命名是有规范的
- 不要以数字开头
- 类名要有意义,不要出现类似:box1 box2 box3 box4 a b c d e
- productitem 复合单词要加连接符 product-item product_item
一个元素类名可以有多个
<标签名 class="类名 类名2 类名3 类名4 类名n"></标签名>
2.2. 类选择器的使用
www.pianshen.com/article/982…
如果要使用类选择器,需要给类名前添加.,未来我们会经常使用类选择器。
.类名 {
}
<!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>
.text {
color: red;
}
</style>
</head>
<body>
<!-- <标签名 class="类名"></标签名> -->
<p class="text">文字</p>
<div>文字</div>
<span class="text">文字</span>
<p>文字</p>
</body>
</html>
3. id选择器
前期没有那么的重要
如果我们想精确找到某个元素,可以使用id。id和类名一样,需要我们自己给标签上添加id属性。
<标签名 id="id值"></标签名>
id的命名规范和class一样。
想要使用id选择器,我们需要加#
#id {
}
在一个网页上,同样的id有且只能有一个。虽然在网页上哪怕有相同的id,css也能都添加样式,但是不要这么用。
4. 后代选择器
因为基础的三个选择器选择范围不好控制,所以结合其他的选择器可以让我们更精确的查找元素。
如果我们想要缩小选择范围,则使用该选择器。
祖先选择器 后代选择器 {
}
当选择时,只选择属于祖先选择器内部的后代元素
<!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>
/* p {
color: red;
} */
/* .box p {
color: red;
} */
/* .box span {
color: red;
} */
.box p span {
color: red;
}
</style>
</head>
<body>
<div class="box">
<p>文字
<span>p中的span</span>
</p>
<span>box中的span</span>
</div>
<div>
<p>文字</p>
<span>文字</span>
</div>
</body>
</html>
5. 群组选择器
如果我们要同时给多个不同选择器设置相同的样式时,可以使用群组选择器
选择器1, 选择器2, 选择器3, 父选择器 后代选择器 {}
逗号中的选择起独立存在
父选择器 后代选择器, 选择器2 {}
上面写法代表
父选择器 后代选择器 {}
选择器2 {}