Combining Advanced CSS Selectors

If you are trying to familiarize yourself with all the cool tricks that CSS3 can offer, I cannot recommend another post as highly as this one from Smashing Magazine.

One cool thing that you can do with advanced CSS selectors is chain them together to create amazingly advanced selections within your documents. This post is just a quick overview of selection tricks you can do to make your life a bit easier at times when you come across difficult styling issues.

We are going to use this code as a sample:

<div class="second third fourth">Words 1</div>
<div class="first second third">Words 2</div>
<div class="first second third">Words 3</div>
<div class="first second third fourth">Words 4</div>

As a quick example, if we write the following CSS:

div[class*="fourth"]{
background-color:#666666;
}

This CSS rule will select any div that has the class “fourth.” Our result will look like this:

Using one styling ruleIf we modify that rule to look like the following:

div[class*="fourth"][class^="second"]{
background-color:#666666;
}

We will get the results that look like this:

A CSS rule with 2 selectors

Using the ^ symbol as we did above is the rule condition that states that is must being with the specified content. In this case, the class of the chosen element must begin with the word “second.”

I won’t make this post very long, but you can easily chain these advanced selectors when you need to hit specific elements in your page. Especially if elements are dynamically created.

Questions or comments, ask below!