Search code examples
csscss-selectors

Style element based on number of children the child has


I know I can style an element in CSS based on how many children it has with the :has() pseudo-class:

.wrapper:has(> :last-child:nth-child(3)) { 
  background-color: red;
}

However, in my case, the HTML looks like this:

<div class='list'>
  <div class='wrapper'>
    <span>Element1</span>
    <span>Element2</span>
    <span>Element3</span>
  </div>
</div>

I want to style the list class dependent on how many elements there are.


Solution

  • This snippet colors the background of .list depending on how many children .wrapper has. It has added that it wants .wrapper to be the first-child of .list as that's what it is in the given code.

    .list:has(.wrapper:first-child > :last-child:nth-child(3)) {
      background-color: red;
    }
    <div class='list'>
      <div class='wrapper'>
        <span>Element1</span>
        <span>Element2</span>
        <span>Element3</span>
      </div>
    </div>

    Note: if any old wrapper inside list is what is required then delete :first-child