Share this:

Under-used and Under-appreciated CSS Selectors Part 1 of 3

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<form>

<h2>Log In</h2>

<div>

<label for="username">Username</label>

<input type="text"placeholder="Username"name="username"/>

</div>

<div>

<label for="username">Password</label>

<input type="password"placeholder="Password"name="pword"/>

</div>

<div>

<input type="checkbox"name="remember"/>

<label for="remember">Remember me</label>

</div>

<div>

<input type="submit"value="Log In"/>

</div>

</form>

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.

1

2

3

4

<style>

input {display:block;}

form div + div {margin-top:15px;}

</style>

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:

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.