CSS教程
CSS进阶

CSS 选择器

CSS选择器用于 选择要设置样式的内容。选择器是CSS规则集的一部分。 CSS选择器根据其ID、类、类型、属性等选择HTML元素。
CSS中有几种不同类型的选择器。
CSS元素选择器 CSS ID选择器 CSS CLASS选择器 CSS通用选择器 CSS组选择器

1)CSS元素选择器

元素选择器通过名称选择HTML元素。
<!DOCTYPE html>
<html>
<head>
<style>
p{
    text-align: center;
    color: blue;
}
</style>
</head>
<body>
<p>此样式将应用于每个段落。</p>
<p id="para1">我也是!</p>
<p>还有我!</p>
</body>
</html>
输出:

此样式将应用于每个段落。

我也是!

还有我!

2)CSS ID选择器

id选择器选择HTML元素的id属性以选择特定元素。 id在页面内始终是唯一的,因此可以选择一个唯一的元素。
它是用井号(#)和元素ID编写的。
我们以id为" para1"的示例为例。
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
    text-align: center;
    color: blue;
}
</style>
</head>
<body>
<p id="para1">您好 lidihuo.com。</p>
<p>此段不会受到影响。</p>
</body>
</html>
输出:

您好lidihuo.com。

此段不会受到影响。

3)CSS CLASS选择器

CLASS选择器选择具有特定类属性的HTML元素。它与"."号一起使用,"."后跟类名。
注意:类名不应以数字开头。
让我们以"center" class为例。
<!DOCTYPE html>
<html>
<head>
<style>
.center {
    text-align: center;
    color: blue;
}
</style>
</head>
<body>
<h1 class="center">此标题是蓝色且居中对齐。</h1>
<p class="center">此段落为蓝色且居中对齐。</p>
</body>
</html>
输出:

此标题是蓝色且居中对齐。

此段落为蓝色且居中对齐。

特定元素的CSS类选择器

如果要指定仅影响一个特定HTML元素,则应将元素名称与类选择器一起使用。
我们来看一个例子。
<!DOCTYPE html>
<html>
<head>
<style>
p.center {
    text-align: center;
    color: blue;
}
</style>
</head>
<body>
<h1 class="center">此标题不受影响。</h1>
<p class="center">此段落是蓝色且居中对齐。</p>
</body>
</html>
输出:

此标题不受影响。

此段落是蓝色且居中对齐。

4)CSS通用选择器

通用选择器用作通配符,它选择页面上的所有元素。
<!DOCTYPE html>
<html>
<head>
<style>
* {
   color: green;
   font-size: 20px;
}
</style>
</head>
<body>
<h2>这是标题。</h2>
<p>此样式将应用于每个段落。</p>
<p id="para1">我也是!</p>
<p>还有我!</p>
</body>
</html>
输出:

这是标题

此样式将应用于每个段落。

我也是!

还有我!

5)CSS组选择器

分组选择器用于选择所有具有相同样式定义的元素。
分组选择器用于最小化代码。逗号用于分隔分组中的每个选择器。
让我们看看没有分组选择器的CSS代码。
h1 {
    text-align: center;
    color: blue;
}
h2 {
    text-align: center;
    color: blue;
}
p {
    text-align: center;
    color: blue;
}
如您所见,您需要为所有元素定义CSS属性。可以按以下方式将其分组:
h1,h2,p {
    text-align: center;
    color: blue;
}
让我们看看CSS组选择器的完整示例。
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
    text-align: center;
    color: blue;
}
</style>
</head>
<body>
<h1>Hello lidihuo.com</h1>
<h2>Hello lidihuo.com (较小的字体)</h2>
<p>这是一个段落。</p>
</body>
</html>
输出:

Hello lidihuo.com

Hello lidihuo.com(较小的字体)

这是一个段落。

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4