logo
post image

Selecting Sibling Elements with CSS

This tutorial will discuss how to select sibling elements of a specific element with CSS.

Selecting Only the Next Sibling with Adjacent Sibling Combinator ( + )

The + character used in CSS is a combinator — it combines 2 CSS selectors. It selects the second element, only if it is just after the first element, and both elements are children of the same parent.

It is to be noted that the second element should come immediately after first element. If there is another element is between, this won't work.

Example 1 :

<div class="main">
	<div id="child-1">Child 1</div>
	<div id="child-2">Child 2</div>
</div>
/* "#child-2" is selected */
#child-1 + #child-2 {
	padding: 10px 0;
}

Example 2 :

<div class="parent">
	<span class="one">One</span>
	<span class="two">Two</span>
	<span class="three">Three</span>
</div>
/* nothing is selected, as ".one" is not immediately followed by ".three" */
.one + .three {
	border: 1px solid black;
}

Selecting Sibling in Any Position with General Sibling Combinator ( ~ )

The ~ character combinator combines 2 CSS selectors. It selects the second element, if it is a sibling of the first element. Both should be children of the same parent.

Unlike the + combinator, the second element just needs to be any sibling, and not compulsorily followed after the first element.

Example 1 :

<div class="main">
	<label class="label">First</label>
	<span></span>
	<img class="img" src="img2.jpg" />
</div>
/* ".img" is selected */
.label ~ .img {
	width: 300px;
}

Example 2 :

<div class="parent">
	<span class="one">One</span>
	<span class="two">Two</span>
	<span class="three">Three</span>
</div>
/* ".three" is selected */
.one ~ .three {
	border: 1px solid black;
}