我有一个html文件,看起来像这样:
<div class="my_class">
<h1>gets styled and that's good</h1>
<h1>doesn't get styled and this is intended</h1>
<div class="my_other_class">
<h1>but this also get styled, but shouldn't</h1>
</div>
</div>
<div class="my_class">
<h1>do style</h1>
<h1>don't style</h1>
<div class="my_other_class">
<h1>shouldn't but does</h1>
</div>
</div>
现在我使用.my_class h1:first-of-type {...}
来设置第一个h1
的样式。然而,第三个也得到了风格,不应该。
有没有办法只选择第一个h1
?
答案 0 :(得分:9)
使用儿童组合子>
。
.my_class > h1:first-of-type {
color: red;
}
<div class="my_class">
<h1>gets styled and that's good</h1>
<h1>doesn't get styled and this is intended</h1>
<div class="my_other_class">
<h1>but this also get styled, but shouldn't</h1>
</div>
</div>
答案 1 :(得分:5)
使用child selector:>
:
.my_class > h1:first-of-type {...}
.my_class > h1:first-of-type {
color: red;
}
&#13;
<div class="my_class">
<h1>gets styled and that's good</h1>
<h1>doesn't get styled and this is intended</h1>
<div class="my_other_class">
<h1>but this also get styled, but shouldn't</h1>
</div>
</div>
<div class="my_class">
<h1>do style</h1>
<h1>don't style</h1>
<div class="my_other_class">
<h1>shouldn't but does</h1>
</div>
</div>
&#13;
答案 2 :(得分:1)
从chipChocolate.py获取答案。但为了完整起见,请看一下:
div, p Selects all <div> elements and all <p> elements
div p Selects all <p> elements inside <div> elements
div > p Selects all <p> elements where the parent is a <div> element
答案 3 :(得分:0)
另一种方法是使用:first-child
伪元素:
.my_class > h1:first-child {
color: red;
}
p {
font-size:2em;
}
div div {
margin-left:50px;
}
&#13;
<p>Main Div 1</p>
<div class="my_class">
<h1>gets styled and that's good</h1>
<h1>doesn't get styled and this is intended</h1>
<p>Sub Div 1</p>
<div class="my_other_class">
<h1>but this also get styled, but shouldn't</h1>
</div>
</div>
<p>Main Div 2</p>
<div class="my_class">
<h1>do style</h1>
<h1>don't style</h1>
<div class="my_other_class">
<h1>shouldn't but does</h1>
</div>
</div>
&#13;