Posted almost 6 years ago. Visible to the public. Linked content.

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

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:

Copy
.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.

Copy
.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:

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

Examples

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
almost 2 years ago
by Jakob Scholz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more