CSS Combinators, make your CSS works easier (+,~, ,>)

Four combinators [Adjacent Sibling(+), General Sibling(~), Child(>), Descendant( )]

When set CSS Styles, below syntax is a basic.

h1 {
  color:#FFFF11;
  background: #000000;
}

.subTitle {
  font-size:13px;
  color:#FFFFFF;
  font-family:inherit;
}

#timeLine {
  background:gray;
}

But when you want to set Styles to a specific tag, using combinators is a smart selection.

combinators are mixed Styles. like ‘div + h1’ or ‘div > span’.

Any tags are mixable and there are four combinator types.

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

1. Adjacent Sibling (+)

Adjacent Sibling uses + mark when specifies one element right after designated element.

h1 + p {
  color:orange;
}

Result is shown below.

<div>
  <h1>I'm h1 tag</h1>
  <p>I'm orange</p>
  <h2>I'm h2 tag</h2>
  <p>I'm a second p tag</p>
  <h1>I'm h1 tag again</h1>
  <p>I'm orange too</p>
<div>

There are two conditions for adjacent sibling.

Element should share the same parent and second element has to come only if right after first element.

In the above HTML result, there are three <p> tag lines but only two lines are matched to the condition.

Therefore only two matched elements are working as mentioned.

2. General Sibling (~)

General Sibling uses ~ mark when specifies elements come after designated element.

h1 ~ p {
  color:orange;
}

Result is shown below.

<div>
  <h1>I'm h1 tag</h1>
  <p>I'm orange</p>
  <h2>I'm h2 tag</h2>
  <p>I'm orange too</p>
<div>

There are two conditions for general sibling.

Element should share the same parent and second element has to come after first element.

In the above HTML result, every <p> tag after <h1>tag is working.

3. Child (>)

Use > marks when express child elements.

div > p {
  color:orange;
}

Result is shown below.

<div>
  <h1>I'm just h1 tag</h1>
  <p> I'm colored orange</p>
  <span>
    <p>I'm not the one</p>
  </span>
  <p> I also am colored orange</p>
</div>

Second element has to be a direct child of first element.

In the above HTML result, only two direct child lines are working.

Fifth line is not working because its position is parent-child-child.

4. Descendant

Use space when express descendant elements.

div p {
  color:orange;
}

Result is shown below.

<div>
  <h1>I'm just h1 tag</h1>
  <p> I'm colored orange</p>
  <span>
    <p>Count me in</p>
  </span>
  <p> I also am colored orange</p>
</div>

As long as second element is a descendant of the first element, every matched line is working.


Combinators are easy and simple for efficient CSS work.

I hope this post is helpful to your CSS design.