CSS Combinators: Types and How to use them?

The CSS combinators are used to explain the relationship between two CSS selectors. The CSS selectors are the methods to select a particular element from a class for styling purposes. CSS selectors may vary from simple ones to complex ones consisting of one or more than one selector connected through a combinator.

WHAT ARE THE TYPES OF COMBINATORS?

There are 4 types of combinators available in CSS:

  • General Sibling Selector ( ~ )
  • Adjacent Sibling Selector ( + )
  • Child Selector ( > )
  • Descendant Selector ( space )

GENERAL SIBLING SELECTOR:

This element is used to select the element that is followed by the elements of the first selector and both of them have the same parent. It is very useful when we have to select the sibling of an element even if they are not adjacent directly.

Suppose, to select all the <p> elements that are siblings to <div> then we write as,

div ~ p {

style properties

}

ADJACENT SIBLING SELECTOR:

It is used as a separator between the elements. It matches the second element only when the element immediately follows the first element, and both of them are children of the same parent. This sibling selector selects the adjacent element, or we can say that the element is next to the specified tag.

Suppose, to select the paragraph that comes immediately after another paragraph, then by using the adjacent selector,

p+p {

style properties

}

CHILD SELECTOR:

It selects the direct descendant of the parent. It selects the second selector only when the first selector is its parent.

The parent element must always be placed at the left of the “>”.

element > element {

style properties

}

DESCENDANT SELECTOR:

The descendant selector is used to match the descendant elements of a particular element and represent it using a single space.

It combines two selectors in which the first selector represents parent, and the second selector represents descendants. The elements matched by the second selector are selected if they have an ancestor element that matches the first selector.

Like so,

element element {

style properties

}

CONCLUSION:

Combinators are extremely useful when you intend to target specific parts of your document, but it’s difficult to reuse the CSS code elsewhere because it’s solely for that specific part in your HTML document. It is advisable to create classes with semantic names that are reusable.

Written by: Salman Ahmed Qureshi

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store