Call
608.845.2900
Visit
330 Locust Dr.
Verona, WI 53593
Message
info@powderkegwebdesign.com
Powderkeg Web Design
Menu
Message Us
Nick
Nick

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

November 16, 2016

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.

 

 

Nick
Nick
Lead Developer

Nick is an ambitious and versatile developer with a wide range of talents. He is an efficient coder that utilizes his resources in order to achieve both his and the clients’ goals. His Alma Mater is the University of Wisconsin – Stevens Point where he graduated with honors in Web and Digital Media Development.