0

I have a bunch of children elements inside main id. 2 elements have a same class name: square. I need to style only the first square (let say make it in red background), so I count how many elements above it and use pseudo. It works, but later on if someone else add more elements above this class, it will break the logic and my pseudo won't work, anymore.

I look for a dynamic way to style the first square. Please take a look at my sample below and please give me a hand

.square {
  width: 100%;
  height: 30px;
  border: 1px solid gray;
}

.square:nth-child(7) {
  background: red;
}
<div id="main">
  <script></script>
  <link>
  <p>
    Some test here
  </p>
  <p>
    Some test there
  </p>
  <div>
    More element here
  </div>
  <p>
    More element there
  </p>
  <div class="square"></div>
  <div class="square"></div>
  <p>
    More element down here
  </p>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
abcid d
  • 2,821
  • 7
  • 31
  • 46
  • This explanation can help you understand the solution: https://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class – Martin Gainza Koulaksezian Sep 29 '20 at 17:25
  • @Martin, Thank you for that link, it is a great knowledge about :first-child, :first-of-class, :first-of-type, nth-of-type(). However, my question is different. – abcid d Sep 29 '20 at 17:50

0 Answers0