CSS is a vast ocean of possibilities. There are dozen different ways to accomplish the look/feel of a design. Lost in this sea of colors, fonts, and positions are a few under-used and under-appreciated selectors. Today we’re going to cover 1 of my 3 favorites.

*We’re making the assumption that we are all now using modern web browsers with the latest CSS specs.

1. + Immediate Sibling Selector

The sibling selector (+) is used to select the next immediate element in the dom tree if it matches your selector.

Pretend we have a login form, and on that form we have a username, password, and “remember” me input:

o_7ki0dd

We would like be able to set some general styles that can be applied to most forms on our site so that we don’ have to redefine the same styling all the time. We want to add some spacing between inputs but not to the last one since that would push our content up needlessly. Essentially what we want is to add a margin-top to any div inside the form that is an immediate sibling to another.

rrceezzg

Here’s another scenario:

Say you use <h2> tags throughout your site to portray page sections. You typically want the section title to have certain spacing to separate it from the body text, but only if it is followed by body text. In that case you can use the sibling selector to select the body text only if it follows an <h2> tag and apply a margin-top:

2gmkqj3q

Now there is a universal rule out there that will automatically apply the spacing between an <h2> tag and an element with the “body” class. You can use the “body” class elsewhere without that margin being applied as well.

The whole idea behind these selectors, at least to me, is to minimize the different ways you have to code the same thing based on certain circumstances. It makes for cleaner, smaller, and less messy code.