Press "Enter" to skip to content

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:

o_7ki0ddwww.powderkegwebdesign.com/wp-content/uploads/2016/11/o_7ki0dd-100×100.png 100w, www.powderkegwebdesign.com/wp-content/uploads/2016/11/o_7ki0dd-182×185.png 182w” sizes=”(max-width: 218px) 100vw, 218px” />

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.

rrceezzgwww.powderkegwebdesign.com/wp-content/uploads/2016/11/rrceezzg-300×256.png 300w, www.powderkegwebdesign.com/wp-content/uploads/2016/11/rrceezzg-317×271.png 317w, www.powderkegwebdesign.com/wp-content/uploads/2016/11/rrceezzg-288×246.png 288w, www.powderkegwebdesign.com/wp-content/uploads/2016/11/rrceezzg-217×185.png 217w” sizes=”(max-width: 321px) 100vw, 321px” />

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:

2gmkqj3qwww.powderkegwebdesign.com/wp-content/uploads/2016/11/2gmkqj3q-300×113.png 300w, www.powderkegwebdesign.com/wp-content/uploads/2016/11/2gmkqj3q-251×95.png 251w” sizes=”(max-width: 434px) 100vw, 434px” />

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.