[英]css first-of-type under other class
我有一个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
?
使用儿童组合器>
。
.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>
使用子选择器 : >
:
.my_class > h1:first-of-type {...}
.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> <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>
从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
另一种方法是使用:first-child
伪元素:
.my_class > h1:first-child { color: red; } p { font-size:2em; } div div { margin-left:50px; }
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.