Explain Codes LogoExplain Codes Logo

Select first occurring element after another element

html
css-selectors
sibling-selectors
css-advanced-techniques
Alex KataevbyAlex Kataev·Oct 11, 2024
TLDR

Immediately target the first <p> following an <h2> with the CSS + selector:

h2 + p { /* add here stylish hat that only <p> right after <h2> can wear! */ }

This CSS snippet ensures only the directly adjacent p is selected.

Deep dive into sibling selectors

This section demystifies two key CSS sibling selectors: Adjacent (+) and General (~).

The Adjacent sibling selector (+)

  • This selector selects an element immediately after another within the same parent.
  • Ideal for styling neighboring elements, such as menu items in a navigation bar.
  • It's like the picky eater who'll eat only the burger that comes directly after fries.
li + li { /* this li says to previous li: bro, can you pass the ketchup? */ }

The General sibling selector (~)

  • This selector works when an element follows another, ignoring if others are in between.
  • You'd use this selector for highlighting warnings following important notices.
  • It's like the spotlight on a stage, beaming on every actor that follows.
h2 ~ p.warning { /* this spotlight makes even the bashful <p class="warning"> blush */ }

The select all sibling elements trick

Sometimes, you might need to select any element immediately following another, consider adding a *:

h2 + * { /* the wildcard cousin at family reunion, who bonds with everyone */ }

Compatibility concerns

The general sibling selector ~ has excellent support, proven to work smoothly in IE7 and onwards. Like a trusted Swiss Army knife, keep it handy and it won't fail you.

Cracking the codes: Advanced techniques with sibling selectors

Let's kick up our game a notch and venture into more advanced situations.

:first-of-type: Precise targeting by type

Suppose you need the first p following a h4, irrespective of other meddling elements:

h4 ~ p:first-of-type { /* staking a 'FIRST' flag on Everest… but for <p> after <h4> */ }

This snippet hones in on the very first p that treads after h4.

The combo move: Sibling selectors + pseudo-classes

Imagine you want to style only a p that's both following an h4 and is also the first child of a parent:

h4 + p:first-child { /* The promising gymnast that wins gold on the debut appearance! */ }

Bear in mind though, :first-child is a rookie with a special use-case: mainly for selecting first child within a parent.

Advanced scenarios: Sibling selectors within complex structures

When conjuring styles within a complex structure like a shadowbox, recall that sibling relationships hinge on shared parent elements.

.shadowbox h2 + h3 { /* Flavoring the sidekick <h3> that emerges from the shadow of <h2> */ }

Congratulations! You've now mastered the arcane art of wrangling sibling selectors!