CSS Combinators: A Guide

CSS combinators are the symbols used in your CSS rules that explain the relationship between selectors. Combinators make it easier to select really specific HTML elements, or to select only one or a few of the same tag type without having to resort to using classes or IDs. The CSS combinators are as follows:

Space

Join us in our newest publication:

Using a space as a CSS combinator is pretty common. Placing a space in between two selectors means that you’re selecting the descendent HTML element, or any element of the second type that is a child the first. So if you want to select every h1 that follows a div, you would use code similar to the code below:

  1. div h1{
  2. color: #555;
  3. }

The code above wouldn’t select every h1 tag, only the h1 tags whose parents are divs.

 +

The plus sign combinator selects adjacent siblings. This means that the two elements must be direct siblings (have the same parent element), and the second one must come right after the first. So let’s say you wanted to select all p tags that have the same parents as an h1 and are placed right after an h1. Here’s how that would look:

  1. h1 + p{
  2. font-size: 26px;
  3. }

 >

The > sign indicates the child selector. Placing this sign in between two selectors means that you are trying to select the immediate child of the first element. To select all a tags that are direct children of p tags, your CSS would need to look like this:

  1. p > a{
  2. text-decoration: none;
  3. }

~

The final combinator in this guide is the general sibling combinator. This symbol can be used to select any siblings of an element (it doesn’t have to be an adjacent sibling like with the + symbol). As long as the two elements share a parent element, you can use the ~ symbol to select the sibling:

  1. h1 ~ p{
  2. font-weight: bold;
  3. }

Share and Enjoy !

0Shares
0 0