HomeThe ClassicsFarai's Codelab

Some Uses of The Adjacent Sibling Selector (+) in CSS

Published:

The adjacent sibling is a selector which matches an element if it directly follow another. For instance:

<style>
    h2 + p {
        color: red;
    }
</style>
<h2>The <code>p</code> tag below should be red</h2>
<p>And I'm surely red!</p>

Since the paragragh is directly after the h2, it’ll be targeted by the h2 + p selector giving it the text color red.

I haven’t used it much until this year where I learned just how powerful it is. Here’s a few uses I’ve found for it. I may keep this updated as I find more uses.

Adding Custom Styling To A Radio Button (Or Any Input Element)

I’ve just finished reading Inclusive Design Patterns by Heydon Pickering and one thing he mentioned is how to use the adjacent sibling selector to improve form input styling. Coincidentally, I found a post by Linsday Kopacz on creating custom keyboard accessible radio buttons. Here’s a pen showing this in action by Elizabeth Schafer.

I’m hoping to try this on one of my personal projects soon!

Consistent Padding and Margins With The Lobotomized Owl

Another thing I got from Heydon was from his other book (co-written by Andy Bell) Every Layout where you can stack elements with consistent margins using the lobotomized owl selector (* + *). While it’s an opinionated approach to ensuring consistent margins, I like it since it leverages CSS’s strengths and applies padding based on