Read more

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

Arne Hartherz
March 19, 2015Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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

Posted by Arne Hartherz to makandra dev (2015-03-19 12:07)