gets styled and that good...">

Css first-of-type under another class

I have a html file that looks something like this:

<div class="my_class">
    <h1>gets styled and that 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>

      

now i use .my_class h1:first-of-type {...}

to create the first one h1

. However, the third also gets style and shouldn't.

Is there a way to select only the first one h1

?

+3


source to share


4 answers


Use child selector : >

:

.my_class > h1:first-of-type {...}

      



.my_class > h1:first-of-type {
  color: red;
}
      

<div class="my_class">
  <h1>gets styled and that 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 codeHide result


+5


source


Use a combinator for kids >

.



.my_class > h1:first-of-type {
  color: red;
}
      

<div class="my_class">
  <h1>gets styled and that 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 codeHide result


+9


source


take the answer from chipChocolate.py. But for the sake of completeness, this:

    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

      

+1


source


Another approach would be to use a pseudo-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 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>
      

Run codeHide result


0


source







All Articles