Descendant Selectors in CSS

Descendant selectors in CSS are both one of the most simple and most sophisticated of the tools in the CSS toolbox. Descendant selectors are simple to understand and grasp. At the same time, using them well and efficiently is one of the more sophisticated skills a designer can possess.

First, a look at the  simple part. A descendant selector (also known as a contextual selector)  select elements on a web page that exist only in a certain context or within a certain structural section of a document. For example, the rule

#maincontent li {list-style-type: square;}

will select only the list items that are contained within (or are descended from) a div with the id maincontent. This rule will style every list item that is the direct descendant of the container div. List items in other structural parts of the page will not be affected.

The selector part of the rule–#maincontent li–is a space separated list of two or more selectors.

Nothing needs to be added to the HTML to make this happen, so it styles the lists without any application of class values or other added HTML. Your HTML is clean and uncluttered, saving bandwidth.

The sophisticated part of the descendant selector technique is knowing how to apply it for maximum benefit. It can eliminate the need for many classes that often get applied to HTML elements to create appearances that could more cleanly be achieved with a descendant selector.

For example, suppose you wanted a paragraph style of one type for your blog posts and another paragraph style for the material in your page footer. You could create two classes for this and apply these classes to every paragraph you wrote. But, with a descendant selector, all that class trash in your HTML could be eliminated with selectors like

.postentry p {font-size: 1em;}

#footer p {font-size: 0.8em;}

Two different paragraph styles, but nothing needed in the HTML to make it happen. Therein lies the sophistication. Instead of applying a class to every list item, write a descendant selector that styles the list items based on their context. Instead of applying a class to every image on a page, create a descendant selector that targets the images based on their context. Instead of adding a class name to every blockquote, create a descendant selector that styles blockquotes based on their position in the page structure.

2 thoughts on “Descendant Selectors in CSS

    • You are absolutely correct, Damien. An ID like maincontent could be assigned to any element on a page. I was presuming that it was a page division meant to hold, well, the main content, but that does not have to be the case.

Leave a Reply