Descendant, Adjacent, Child, Sibling Combinators and Selectors

Coming into second part of Power CSS3 selectors, we will learn here about Descendant, Adjacent, Child, Sibling Combinators and Selectors that make our styling task lots easier.

You should have a look at the first part of CSS3 selectors if you already haven’t read it yet.

Power CSS3 – Descendant, Adjacent, Child, Sibling Combinators and Selectors

1. X Y (Descendant Combinator)

The most used descendant selector or, more accurately, the descendant combinator let you combine two or more selectors so you can be more specific in your selection method. For example:

  • Only anchor tags inside list should have a common style.
  • All li tags inside a specific class should have a specific style.
  • Rather than targeting all span tags, you only need to target the span that are inside thumb class.

A quick note: Don’t apply much weight on selectors whenever you not need, so get rid of selectors looking like ul.thumb li a img.round-img  or P Q R M N.my-class.

View Demo | Compatible with: IE6+, Firefox, Chrome, Safari, Opera

2. X + Y (Adjacent Combinator)

An adjacent sibling combinator uses the plus symbol (+). It will select only the element that is immediately preceded by the former element means the targeted element must be an immediate sibling. This CSS code below will make all first paragraph after each h2 tag to appear in green:

View Demo | Compatible with: IE7+, Firefox, Chrome, Safari, Opera

3. X > Y (Child Combinator)

The difference between the descendant combinator X Y and child combinator X > Y is that the latter will only select direct children. For example, consider the following markup.

A selector of #container > ul will only target the two uls which are direct children of the div with an id of container. It will not target, for instance, the ul that is a child of the first li.
This selector can come in handy when styling nested lists and recommended when working with JavaScript-based CSS selector engines .

View Demo | Compatible with: IE7+, Firefox, Chrome, Safari, Opera

4. X ~ Y (Sibling Combinator)

This sibling combinator is a generalization of  adjacent combinator and is less strict. It will select all the later elements as long as they follow the former selector.

In the example the style will be applicable to all the paragraph except the one who is wrapped inside a div.

View Demo | Compatible with: IE7+, Firefox, Chrome, Safari, Opera


So it’s second part in this series where you have learned about the power of Descendant, Adjacent, Child, Sibling Combinators and Selectors.

Let’s continue with attribute selectors followed by pseudo-class and pseudo-element.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.