{justCSS}

Just plain CSS

est. 2015

CSS Sibling Selectors

In my previous post I touched on sibling selectors without explaining in too much detail what that means – I’m not going to go into too much detail here either, but I do think it warrants a slightly longer explanation with some examples.

There are two types of sibling (yes … as in: descendants of the same parent) selectors:

  1. Adjacent sibling indicated with a plus sign ( + )
  2. General sibling indicated with tilde ( ~ )

As already explained: elements need the same parent to be considered siblings – i.e.

<div class="parent">
    <div class="child">I am a child of my parent</div>
    <div class="child">I am a child of my parent, so I am the other child's sibling</div>
</div>

… simple enough – we can use sibling selectors to select elements that follow on another.

Adjacent sibling selector

.firstchild + .sibling{
  color: red;
  font-weight: bold;
}

See the Pen MwwKqX by Jacques Mostert (@jayx) on CodePen.14523

General sibling selector

.firstchild ~ .sibling{
  color: red;
  font-weight: bold;
}

See the Pen pJJgQV by Jacques Mostert (@jayx) on CodePen.14523

… and there you have it – also …

Notes on use:
NO! you cannot select elements preceding their siblings, so don’t ask … it’s been in and out of draft for CSS4, but I’m not holding my breath. Check out browser support for the adjacent sibling selector and the general sibling selector (well supported) and put it to good use. Comments open – GO!

Leave a Reply

Your email address will not be published. Required fields are marked *