BASEWEBMASTER

Brought To You By
Tomlin Ventures Ltd

Using The Child Selector

Using Child selectors or direct descendants

The CSS child selector or direct descendant selector as it is sometimes known functions in much the same way as the descendant selector in that it effects elements which occur within other specified elements.

The difference with the child selector is that instead of effecting all occurrences of an element it will effect only direct descendants of an element.

Take a look at the example below the markup of the child selector is slightly different to that of other previously encountered CSS selecors. Using the > symbol you assign your child selectors like.

p > span

This will result in only direct span descendants of the paragraph element being styled.

The following example shows how a child selector would effect a HTML document tree.

CSS
p > span			{font-weight: bold;}

So any span element which appears directly beneath the Paragraph element in the document tree will be styled, element that occur within the paragraph element but that are not directly beneath it will not be effected, as shown.

span child selector

Using Child Selectors With IDs And Classes

As with other CSS selectors the child selector may also utilise the ID and class attributes and can therefore be used in multiple situations. The code in this case would look like this.

.highlight > span {color: blue;}

The above would effect any direct span descendant of any element carrying the highlight class attribute.

Child Selector Worked Example

A great example of when you might want to use child selectors for your styling would be when styling embedded lists as they tend to have many repetative code sequences often needing different styles depending on where they appear in the document tree.

Look at the following code.

HTML
<ul>
<li>Computers
	<ol>
	<li>Desktop</li>
	</ol>
</li>
<li>Phones
	<ol>
	<li>Apple</li>
	<li>Nokia</li>
	<li>Samsung</li>
	</ol>
</li>
<li>Electricals
	<ol>
	<li>MP3 Player</li>
	<li>Iron</li>
	</ol>
</li>
<li>Clothes
	<ol>
	<li>Tops</li>
	<li>Trousers</li>
	<li>Skirts</li>
	<li>T-Shirts</li>
	</ol>
</li>
</ul>

Without any style information it would appear as shown below.

unstyled embedded lists

By adding a few simple lines of CSS using type selectors the child selectors you can transform it to this.

styled embedded lists

As you can see this is a fairly basic example designed purly to illustrate the usage of the child selectors but it is in fact, the basic structure and style of a totally CSS drop down menu like the one used on this site.

Hit the next article button to continue with the tutorial and learn about adjacent sibling selectors.

Share to Facebook Share to Twitter Digg This Stumble It Share to Reddit Share to Delicious Technorati LinkedIn Google Buzz Blogger More...

blog comments powered by Disqus