CSS基础学习--12 分组 和 嵌套 选择器

一、分组选择器

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

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

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

        每个选择器用逗号分隔

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>CSS基础学习-分组与嵌套选择器</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>

备注:h1、h2与p标签字体颜色都是绿色, 为了尽量减少代码,可以使用分组选择器。

效果图:

 二、嵌套选择器

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

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

  • p{ }: 为所有 p 元素指定一个样式。
  • .marked{ }: 为所有 class="marked" 的元素指定一个样式。
  • .marked p{ }: 为所有 class="marked" 元素内的 p 元素指定一个样式。
  • p.marked{ }: 为所有 class="marked" 的 p 元素指定一个样式。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>CSS基础学习-嵌套选择器</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>

效果图:

猜你喜欢

转载自blog.csdn.net/yyxhzdm/article/details/131198196