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
- Example for last-child: https://jsfiddle.net/1b7cusuw/ Show archive.org snapshot
- Example for adjacent sibling: https://jsfiddle.net/rn7Lwruv/ Show archive.org snapshot
Posted by Arne Hartherz to makandra dev (2015-03-19 11:07)