Home > Software design >  CSS only for first matching element
CSS only for first matching element

Time:10-22

I have multiple repeating div sections containing paragraphs and I want to apply specific CSS only on the first matching paragraph inside the div.

div.example1 p.special~p.special {
  color: green;
}
<p>Top Paragraph</p>
<div class='top'>

  <div class="example1">
    <p class="special">This is paragraph 1 and it should be green and bold</p>
  </div>

  <div class="example1">
    <p class="special">This is paragraph 2</p>
  </div>

  <div class="example1">
    <p class="special">This is paragraph 3</p>
  </div>

</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Here is the link -

CodePudding user response:

The problem With the second css selector you are modifying all p tags that come after a p tag that are inside a div with the class of example1

The solution Instead of targeting the first p tag, target the first .example1 div instead by doing to following:

.example1:first-of-type .special {
  color: green;
  font-weight: bold;
}
<p>Top Paragraph</p>
<div class='top'>

  <div class="example1">
    <p class="special">This is paragraph 1 and it should be green and bold</p>
  </div>

  <div class="example1">
    <p class="special">This is paragraph 2</p>
  </div>

  <div class="example1">
    <p class="special">This is paragraph 3</p>
  </div>

</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Side note try keeping your css selectors as short as possible and strate to the point. avoid doing things like div.class but instead use .class

CodePudding user response:

You can use :nth-child() pseudo class to specify which element in the group of siblings. See :nth-child() Documentation

.example1:nth-child(1) .special {
  color: green; font-weight:bold;
}

Alternatively there is the :first-of-type which will select the first element in the group. See :first-of-type Documentation

.example1:first-of-type .special {
  color: green; font-weight:bold;
}

Both selectors will achieve the same thing for you HTML snippet.

  • Related