其他类下的css first-of-type

The*_*ler 3 html css css-selectors css3

我有一个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>
Run Code Online (Sandbox Code Playgroud)

现在我用.my_class h1:first-of-type {...}第一个样式h1.然而,第三个也得到了风格,不应该.

有没有办法只选择第一个h1

Wea*_*.py 9

使用儿童组合子>.

.my_class > h1:first-of-type {
  color: red;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


j08*_*691 5

使用子选择:>:

.my_class > h1:first-of-type {...}
Run Code Online (Sandbox Code Playgroud)

.my_class > h1:first-of-type {
  color: red;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)