Brought To You By
Tomlin Ventures Ltd

Using Descendant Selectors

Using Descendant selectors to style with CSS.

Much like the CSS type selector the descendant selector is a way of styling on page element based on there HTML tags therefore it is not necessary to provide any document side references like the id or class attribute to use descendant selector.

Unlike the type selectors it is possible to limit the elements that are effected by the CSS regardless of whether they are the same type of element or not.

This limiting factor is achieved by using descendants i.e. elements which appear within other elements as the reference points.

Look at the following two lines of css, at first they appear to very similar and one might assume that they will both style the same elements.

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

The first line of code shows a standard span type selector and will style all span elements on the page with the given style, as shown in the document tree below.

span type selector

The second line of code shows a descendant selector comprising of p span elements. What this represents is any span element which is itself a descendant of the paragraph element. This would effect the document tree as shown below.

descendant span selector

Notice how the span element on the left is not effected by the CSS code as it is not the descendant of a paragraph element.

Also notice how all span elements within the paragraph element on the right are effected. As long as the span element is contained within a p element it does not matter at what level the span element appears it will still be effected.

Thats the descendant selector, as you can see it is very similar in format and function to the type selector but with the additional ability for the webmaster to limit the application of the styles without the need for any inline referencing .

Using Descendant Selectors With IDs And Classes

Above we have stated that one of the greatest benefits of using descendant selectors is that it requires no on page referencing, ids and classes for example. This does not mean that they cannot be used in this way. A descendant may be descended from a class or id just as it can be descended from a specific element.

.highlight span		{color: red;}

The above code will style all span elements that are descended from the highlight class, the class itself could be applied to any element on the page and any span appearing within this element will be styled accordingly, as shown below.

class descendant span selector

This is just as valid a form of using the descendant selector as the first example and may be of more use depending on your own styling methods.

Hit the next article button to continue with the tutorial and learn about child 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