0

I want to select only the first box--highlight.

<ul>
  <li>
    <a class="box "></a>
  </li>
  <li>
    <a class="box box--highlight"></a>
  </li>
  <li>
    <a class="box box--highlight"></a>
  </li>
  <li>
    <a class="box "></a>
  </li>
</ul>

I was trying around with the adjacent siblings combinator but it did not work as expected

li .box--highlight + li .box--highlight {
  color: green;
}

Is this even possible? I was wondering if the answer is already to select the parent selector (which is not possible of course): Is there a CSS parent selector?

  • With Javascript, Yes! – m4n0 Oct 25 '20 at 21:58
  • 1
    This can be done provided the DOM order does not change later. `li:nth-child(2) .box--highlight { color: green; }` – m4n0 Oct 25 '20 at 22:02
  • Can't you give the classes to the `li` element instead? – alihmd Oct 25 '20 at 22:03
  • @m4n0 I am looking for a CSS-only approach though. I can edit the html but then I end up without ```li``` elements and that would not be good semantics wise. The order of items will change, so your suggestion would not work. – browsergarden Oct 25 '20 at 22:10
  • @alihmd this is using a scroll-to js plugin which only accepts ```a``` elements unfortunately. – browsergarden Oct 25 '20 at 22:13
  • 1
    CSS cannot do it with that structure, send the class to the parent, then you can set and reset a style fromthere, else javascript. – G-Cyrillus Oct 25 '20 at 22:13
  • @G-Cyrillus thanks for the clear answer – browsergarden Oct 25 '20 at 22:14
  • the shortest way in js i can think off is something alike : `let myfirstboxclassed=document.querySelector('.box--highlight'); myfirstboxclassed.classList.add('styleMe');` where you can style the first class it finds with `.styleMe{/*style*/}` here is a live example : https://codepen.io/gc-nomade/pen/qBNrZeZ – G-Cyrillus Oct 25 '20 at 22:15

1 Answers1

0

As mentioned in the comments above: this is not possible with pure CSS.

My workaround is now to remove the li element.