author: Krasimir Tsonev

Hi there, I'm . Senior front-end engineer with over 13 years of experience. I write, speak and occasionally code stuff. Follow me on Twitter, GitHub, Facebook or LinkedIn

CSS: selecting a specific child

The selectors are one of the most powerful features in CSS. Sometimes they can save you a lot of additional work. In this article I'll show you how to set the style of a specific child in a list of elements.

The example's html code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
      <title></title>
    </head>
    <body>
      <div id="main">
      <span>aaaaa</span>
      <span>bbbbb</span>
      <span>ccccc</span>
      <span>ddddd</span>
      <span>eeeee</span>
    </body>
  </html>

So, let's imagine that we have to set a background color for the "span" tag with "ddddd" content. There are several available solutions with javascript, like this one (jQuery):

$("#main").find("span").eq(3).css("background", "#F00");

That's simple solution, but it requires javascript. We can do that same thing by using only CSS.First, we will select all the "span" childs:

#main > span {	font-family: Verdana;	font-size: 12px;	padding: 3px;}

Changing the style for only the first "span" tag:

#main > span:first-child {	color: #F00;}

And at the end styling the fourth element:

#main > span:first-child + span + span + span {	background: #F00;}

And the result is:[1]

P.S.don't forgot to add a DOCTYPE in your html. The code above works in IE7, IE8, FireFox, Opera, Safari, Chrome

If you enjoy this post, share it on Twitter, Facebook or LinkedIn. Or maybe comment below: