Use CSS sibling selectors instead :last-child (or :first-child)

Updated . Posted . Visible to the public.

Often times you want to give a bunch of elements the same style, except for the last. For example borders or margins.

You probably commonly used the :last-child CSS meta selector like so:

.foo {
  border-bottom: 1px dashed #000;
}
.foo:last-child {
  border-bottom-width: 0;
}

However, this only works when an element is the last child of its parent. Any other siblings which are unrelated to your case will break it.

Instead, prefer using the + sibling selector. It applies to the element following the other.

.foo + .foo {
  border-top: 1px dashed #000;
}

Note how we now use a top border instead of a bottom border. This is because we have to "reverse" the style to mimic the :last-child rule.

The plus sign means "adjacent selector". If you want to reach any subsequent sibling, use a tilde:

.foo ~ .foo {
  border-top: 1px dashed #000;
}

Examples

Arne Hartherz
Last edit
Jakob Scholz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2015-03-19 11:07)