CSS 分组 和 嵌套 选择器 | CSS教程

分组选择器

在样式表中有很多具有相同样式的元素。

h1 {
    color:green;
}
h2 {
    color:green;
}
p {
    color:green;
}

为了尽量减少代码,你可以使用分组选择器。

每个选择器用逗号分隔。

在下面的例子中,我们对以上代码使用分组选择器:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Web176教程(web176.com)</title> 
<style>
h1,h2,p
{
	color:green;
}
</style>
</head>

<body>
<h1>Hello World!</h1>
<h2>Smaller heading!</h2>
<p>This is a paragraph.</p>
</body>
</html>

嵌套选择器

它可能适用于选择器内部的选择器的样式。

在下面的例子设置了四个样式:

  • p{ }: 为所有 p 元素指定一个样式。
  • .marked{ }: 为所有 class=”marked” 的元素指定一个样式。
  • .marked p{ }: 为所有 class=”marked” 元素内的 p 元素指定一个样式。
  • p.marked{ }: 为所有 class=”marked” 的 p 元素指定一个样式。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Web176教程(web176.com)</title> 
<style>
p
{
	color:blue;
	text-align:center;
}
.marked
{
	background-color:red;
}
.marked p
{
	color:white;
}
p.marked{
    text-decoration:underline;
}
</style>
</head>

<body>
<p>这个段落是蓝色文本,居中对齐。</p>
<div class="marked">
<p>这个段落不是蓝色文本。</p>
</div>
<p>所有 class="marked"元素内的 p 元素指定一个样式,但有不同的文本颜色。</p>
	
<p class="marked">带下划线的 p 段落。</p>
</body>
</html>

作者:terry,如若转载,请注明出处:https://www.web176.com/css/5502.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2022年4月13日 下午4:49
下一篇 2022年4月14日 上午11:26

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注