如何从特定类型中获取第一个元素。
h1:first-of-type {
background: red;
}
<h1>Main Title</h1>
<div class="content">
<h1>Another Title</h1>
<div class="para">
<h1>One More Title</h1>
</div>
</div>
我想设置“主标题” h1
,背景为红色。问题是这三个h1
background:red;
如何从特定类型中获取第一个元素。
h1:first-of-type {
background: red;
}
<h1>Main Title</h1>
<div class="content">
<h1>Another Title</h1>
<div class="para">
<h1>One More Title</h1>
</div>
</div>
我想设置“主标题” h1
,背景为红色。问题是这三个h1
background:red;
尝试这个
CSS
.content h1{
background:none;
}
HTML
<h1>Main Title</h1>
<div class="content">
<h1>Another Title</h1>
<div class="para">
<h1>One More Title</h1>
</div>
</div>
如果您只想要 h1 的第一级(而不是任何元素中的第一级),您可以使用子组合器
body > h1 {
background:red;
}
或者您可以将它们组合起来仅获得第一个。
body > h1:first-of-type {
background:red;
}
这当然取决于 html 结构,以及第一个元素h1
是哪个元素的子元素。
我想设置“主标题”h1,背景为红色。问题是所有三个“h1”都带有背景:红色;
如果您只想选择所有“顶级”元素中的第一个 h1 元素,即 body 的直接子元素,请使用
body > h1:first-of-type