CSS 选择器

CSS 选择器用于选择要设置样式的内容选择器是 CSS 规则集的一部分。CSS 选择器根据其 id、类、类型、属性等选择 HTML 元素。

CSS 中有几种不同类型的选择器。

  1. CSS 元素选择器

  2. CSS ID 选择器

  3. CSS 类选择器

  4. CSS 通用选择器

  5. CSS 组选择器

1) CSS 元素选择器

元素选择器按名称选择 HTML 元素。

例子 (Example)

<!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>

2) CSS Id 选择器

id 选择器选择 HTML 元素的 id 属性来选择特定元素。一个 id 在页面内始终是唯一的,因此选择它是为了选择一个唯一的元素。

它用哈希字符 (#) 编写,后跟元素的 id。

让我们举一个id为“para1”的例子。

例子 (Example)

<!DOCTYPE html>  
<html>  
<head>  
<style>  
#para1 {  
    text-align: center;  
    color: blue;  
}  
</style>  
</head>  
<body>  
<p id="para1">你好Rocschool.com </p>  
<p>本段不受影响。</p>  
</body>  
</html>

3) CSS 类选择器

类选择器选择具有特定类属性的 HTML 元素。它与句点字符一起使用。(句号)后跟类名。

注意:类名不应以数字开头。

让我们以“中心”类为例。

例子 (Example)

<!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 元素,那么你应该使用元素名称和类选择器。

让我们看一个例子。

例子 (Example)

<!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 通用选择器

通用选择器用作通配符。它选择页面上的所有元素。

例子 (Example)

<!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 代码。

句法 (Syntax)

h1 {  
    text-align: center;  
    color: blue;  
}  
h2 {  
    text-align: center;  
    color: blue;  
}  
p {  
    text-align: center;  
    color: blue;  
}

如您所见,您需要为所有元素定义 CSS 属性。它可以按以下方式分组:

句法 (Syntax)

h1,h2,p {  
    text-align: center;  
    color: blue;  
}

让我们看看 CSS 组选择器的完整示例。

例子 (Example)

<!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>
上一主题 CSS 语法 下一主题 CSS 如何添加
  • 使用社交账号登录,本站支持
全部评论(0)