Home > Back-end >  CSS - how to get first element of consecutive class
CSS - how to get first element of consecutive class

Time:12-21

I have ten li having same class and between this having 4 consecutive class. how I can get the first element of consecutive class? with CSS

.abc {
  color: red;
}

.abc   .xyz:nth-of-type(1) {
  color: yellow !important;
}
<ul>
  <li >abc</li>
  <li >abc</li>
  <li >abc</li>
  <li >abc xyz</li>
  <li >abc xyz</li>
  <li >abc xyz</li>
  <li >abc xyz</li>
  <li >abc</li>
  <li >abc</li>
  <li >abc</li>
</ul>

CodePudding user response:

Here you go...

li {
  color: red;
}

li:not(.xyz)   .xyz {
  color: blue;
}
<ul>
  <li >abc</li>
  <li >abc</li>
  <li >abc</li>
  <li >abc xyz</li>
  <li >abc xyz</li>
  <li >abc xyz</li>
  <li >abc xyz</li>
  <li >abc</li>
  <li >abc</li>
  <li >abc</li>
</ul>

CodePudding user response:

To select the first element of consecutive class xyz that follows an element with class abc using CSS, you can use the :first-of-type pseudo-class and the combinator.

Here is an example of how you can select the first element of consecutive class xyz that follows an element with class abc:

.abc   .xyz:first-of-type {
  color: yellow !important;
}

This will apply the color: yellow !important style to the first element with class xyz that immediately follows an element with class abc.

CodePudding user response:

In your case you can fix this another way:

.abc {
    color: red;
}

ul .xyz {
    color: yellow;
}
        
ul > .xyz ~ .xyz {
    color: red;
}
<ul>
  <li >abc</li>
  <li >abc</li>
  <li >abc</li>
  <li >abc xyz</li>
  <li >abc xyz</li>
  <li >abc xyz</li>
  <li >abc xyz</li>
  <li >abc</li>
  <li >abc</li>
  <li >abc</li>
</ul>

Now only the first element with class xyz will be yellow, the other ones will be red.

  • Related