qwelton qwelton - 2 months ago 12
CSS Question

CSS Selector for first matching element

<section class="section-one"></section>
<section class="section-two"></section>
<nav></nav>
<section class="section-three"></section>
<section class="section-four"></section>


Because section order is coming from a CMS, section order is unknown (i.e.,
section-two
and
section-three
could be swapped). I want to select the first sibling section after
section-two
but can't use adjacent sibling selectors as there are potentially other elements between sections.

How can I select the first section following
section-two
considering there could be one or multiple elements between them?

Answer
.section-two ~ section {
  /* Set styles */
}
.section-two ~ section ~ section {
  /* Undo styles */
}

.section-two ~ section {
  background: #0f0;
}
.section-two ~ section ~ section {
  background: transparent;
}
<section class="section-one">One</section>
<section class="section-two">Two</section>
<nav>Nav</nav>
<section class="section-three">Three</section>
<section class="section-four">Four</section>

Comments