CSS 选择器用于选择要设置样式的内容。选择器是 CSS 规则集的一部分。CSS 选择器根据其 id、类、类型、属性等选择 HTML 元素。
CSS 中有几种不同类型的选择器。
CSS 元素选择器
CSS ID 选择器
CSS 类选择器
CSS 通用选择器
CSS 组选择器
元素选择器按名称选择 HTML 元素。
<!DOCTYPE html>
<html>
<head>
<style>
p{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p>这种样式将应用于每个段落。</p>
<p id="para1">我也是!</p>
<p>And me!</p>
</body>
</html>
id 选择器选择 HTML 元素的 id 属性来选择特定元素。一个 id 在页面内始终是唯一的,因此选择它是为了选择一个唯一的元素。
它用哈希字符 (#) 编写,后跟元素的 id。
让我们举一个id为“para1”的例子。
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p id="para1">你好Rocschool.com </p>
<p>本段不受影响。</p>
</body>
</html>
类选择器选择具有特定类属性的 HTML 元素。它与句点字符一起使用。(句号)后跟类名。
让我们以“中心”类为例。
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">此标题为蓝色且居中对齐。</h1>
<p class="center">这一段是蓝色的,居中对齐。</p>
</body>
</html>
如果你想指定只影响一个特定的 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>
通用选择器用作通配符。它选择页面上的所有元素。
<!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>
分组选择器用于选择具有相同样式定义的所有元素。
分组选择器用于最小化代码。逗号用于分隔分组中的每个选择器。
让我们看看没有组选择器的 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>你好 Rocschool.com </h1>
<h2>你好 Rocschool.com(小字体)</h2>
<p>这是一个段落。</p>
</body>
</html>