Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to target direct child selector of parent element

How do I target direct child h2 of div but at the same time make sure any other h2 doesn’t get changed.

At one place I have this markup.

<div class="cms-page-view">
  <div class="column">
    <div></div>
    <div></div>
    <div>
        <h2>Hello</h2>    <!-- Target this -->
        <p>Some Text</p>
    </div>
  </div>
</div>

And at another place, I have this markup.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="cms-page-view">
  <div class="column">
    <div></div>
    <div></div>
    <div>
        <section>
          <div>
           <h2>Hola</h2> <!-- Make sure this does not change -->
           <p>Some Text</p>
          </div>  
        </section>
    </div>
  </div>
</div>

Is there any way to do this without using :first-child or :nth-child().

I tried this but it doesn’t work:

.cms-page-view {
  & .column {
    & div {
      & > h2 {
        color: blue;
      }
    }
  }
}

>Solution :

Assuming you can’t touch your HTML, you can use > multiple times to achieve the result you want

SNIPPET

.cms-page-view .column > div > h2 {
  background: red
}

/* SASS

.cms-page-view {
  & .column {
    & > div {
      & > h2 {
        background: red;
      }
    }
  }
}

*/
<div class="cms-page-view">
  <div class="column">
    <div></div>
    <div></div>
    <div>
      <!-- Target this -->
      <h2>Hello</h2>
      <p>Some Text</p>
    </div>
  </div>
</div>

<div class="cms-page-view">
  <div class="column">
    <div></div>
    <div></div>
    <div>
      <section>
        <div>
          <!-- Make sure this does not change -->
          <h2>Hola</h2>
          <p>Some Text</p>
        </div>
      </section>
    </div>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading