JavaScript Tutorial

CSS Combinators

Combinators maintain relationships between two selectors in different ways, such as targeting the child, parent, and siblings.

There can be more than one simple selector in a CSS selector, and we can include a combinator between these selectors.

There are four ways to combine selectors:

 

General Sibling Selector

The general sibling selector selects all elements that are siblings of a specified element. It uses the tilde (~) symbol to specify the selector.

It is useful when we want to select the siblings of an element, even if they are not directly adjacent.

Input:-

 

Output:-

 

Adjacent Sibling Selector

The adjacent sibling selector matches the second element only when it immediately follows the first element, and both elements are children of the same parent. This sibling selector selects the adjacent element, or we can say the element that is next to the specified tag.

It uses the plus (+) symbol to specify the selector.

It only selects the element that is immediately next to the specified first element.

Input:-

 

Output:-

 

Child Selector

The child selector selects the direct descendant of the parent. This combinator only matches elements that are immediate children in the document tree.

It uses the greater than (>) symbol to specify the selector.

The parent element must always be placed on the left of the ">". If we remove the greater than (>) symbol, it will become a descendant selector.

Input:-

 

Output:-

 

Descendant Selector

The descendant selector is used to match descendant elements of a particular element. It uses a space to specify the selector.

The word "descendant" indicates nesting anywhere in the DOM tree. It can be a direct child or deeper than five levels, but it will still be referred to as a descendant.

It combines two selectors, where the first selector represents an ancestor (parent, grandparent, etc.), and the second selector represents descendants.

Input:-

 

Output:-

 

Go back to Previous Course