Descendant Selector
By Stephen Bucaro
A CSS style sheet consists of rules that define how html elements should be
displayed on a webpage. Each rule consists of one or more selectors, one
or more properties, and one or more values that each property
should be set to.
You can use the descendant selector to select elements that are descendants of
other elements. What if you created a selector to apply to all paragraph elements.
You also want to the rules to apply to paragraph elements that are nested within div
elements, but instead of blue text you want to display red text in paragraphs nested
within divs. You could create a descendant selector as shown below.
p
{
font-family: verdana;
font-size:12px;
font-weight: bold;
color:blue;
}
div p
{
color:red;
}
<p>Paragraph not nested within div</p>
<div>
<p>Paragraph nested within div</p>
</div>
In the code shown above, note the descendant selector which is the parent element
selector separated by a space from the descendant element selector. Descendant
selectors can be also used with class selectors and id selectors.
In the example shown below, the class mystyle sets the text color to blue
for the paragraph outside the div. But the descendant selector sets the text color
to red for the paragraph nested in the div.
.mystyle
{
font-family: verdana;
font-size:12px;
font-weight: bold;
color:blue;
}
.mystyle p
{
color:red;
}
<p class="mystyle">Paragraph not nested within div</p>
<div class="mystyle">
<p>Paragraph nested within div</p>
</div>
In the example below a selector applies to all paragraph elements. The same rules
apply to the paragraph that's nested within the div with the id nav, but instead
of blue text the descendant selector applies the rule to display red text in
paragraphs nested within the div.
p
{
font-family: verdana;
font-size:12px;
font-weight: bold;
color:blue;
}
#nav p
{
color:red;
}
<p>Paragraph not nested within div</p>
<div id="nav">
<p>Paragraph nested within div</p>
</div>
Remember, descendant selectors apply style rules to elements that are contained
within other elements. The descendant selector is the parent element selector
separated by a space from the descendant element selector.
More CSS Quick Reference: • How to Use a CSS ID Selector • CSS Units of Measurement • Grouped Selectors • Set an Element's Overflow • Set the Word Spacing • Use Inline Style • Set a Background Image • Set an Element's Margin • Set the box-sizing Property • CSS background-origin Positions Background
|