Back to all posts

CSS: Combinator selectors


Combinator selectors are a type of CSS selectors that allows you to select based in their realtionship to other element. There are four types of combinator selectors in CSS:

1. Descendant Selectors (space):

This is selector matches all elements that are descendants of a specified parent element. For example, ig you want to select all p elements that are inside a 'div‘ element, you would use following selector:

div p {
  /* Styles */
}

2. Child Selector ( > ):

This selector matches all elements that are direct children of a specific parent element.

For example, if you want to select all `p` elements that are direct children of a `div` element, you would use the following selector:

div > p {
  /* Styles */
}

3. Adjacent Sibling Selector (+):

This is selector matches and element that is immediately following another specified element. For example, if you want to select the first `p` element that comes immediately after a `h2` element, you would use the following selector:

h2 + p {
  /* Styles */
}

4. General Sibling Selector (~):

This selector matches all elements that are siblings of a specified element and come ofter it in html document.

For example, if you want to select all `p` elements that are siblings of a `h2` element and come after you would use the following selector

h2 ~ p {
  /* Styles */
}

Combinator selectors are a powerful way to target specific elements on your page based on their relationship to other elements.