CSS Sibling Selector Tutorial

  • Post author:
  • Post category:CSS

In this section, we will learn what the sibling selector is and how to use it in CSS.

CSS Selector Sibling

The HTML Sibling Selector is a type of a selector that focuses on finding the siblings of an element and tries to style those siblings!

Note: sibling elements are those that are next to each other and all of them are the children of the same parent element.

For example, let’s say you want to style the siblings of an element that has the id value `#checker`; well, using the sibling selector we can easily do that.

There are two types of sibling selector in CSS. So let’s go and see them in details now.

CSS Adjacent Sibling Selector

The first type sibling selector is called Adjacent Sibling Selector. This selector focuses only on finding the very next sibling of an element. So it basically styles one element!

Adjacent Sibling Selector in CSS Syntax:

element + sibling{

//body...

}

`element`: this is the element we want to find its next sibling and style it.

`sibling`: this is the sibling of the element we want to style it.

For example:

`p+ul`{

//body...

}

This example is telling us that browsers should look for every <p> elements in a page and check their very next sibling. If that sibling is `<ul>` element, then the style of the declaration block should be applied to it. Otherwise, that sibling will be skipped.

Example: using adjacent sibling selector in CSS

See the Pen using adjacent sibling selector in CSS by Enjoy Tutorials (@enjoytutorials) on CodePen.

Note: the adjacent sibling selector targets the one sibling that comes after the one we specify in the selector and not the one before!

CSS General Sibling Selector

This type of selector tries to find those sibling elements with a specific type that comes after the declared element.

Note: the main different between this selector and the adjacent selector is that this one won’t care if the very next sibling is not of the specified type! Basically, as long as one of the siblings that come after the target element matches the specified type, then the style of this selector will apply to that element.

General Sibling Selector in CSS Syntax:

element ~ sibling{

//body…

}

`element`: this is the element we’re looking for its siblings in the target HTML document.

`sibling`: this is the element we want to find on the page that is also the sibling of the `element`.

Example: using general sibling selector in CSS

See the Pen using general sibling selector in CSS by Enjoy Tutorials (@enjoytutorials) on CodePen.

Note: the general sibling selector targets those siblings that come after the one we specify in the selector and not those before!

Leave a Reply