Selecting Descendant Elements
Description
The descendant selector selects elements that are contained within another element.
- Selector: firstSelector secondSelector
- Matches: Selects elements that match the secondSelector and are descendants of the elements matched by the firstSelector
- Since CSS Version: 1
Example
The following code shows how to select descendants.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
p span {<!--from ww w . j a v a2 s.c o m-->
border: thin black solid;
padding: 4px;
}
</style>
</head>
<body>
<a id="anchor" class="class1 class2" href="http://java2s.com">
Visit the website </a>
<p>
This is <span lang="en-uk" class="class2">a</span> test.
</p>
<span>another span</span>
<a id="w3canchor" href="http://w3c.org">Visit the W3C website</a>
</body>
</html>
The selector selects span
elements that are descendants of p
elements.
Example 2
A another Descendant Selector Example
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#mytable td {<!--from w w w . ja v a 2 s . c om-->
border: thin black solid;
padding: 4px;
}
</style>
</head>
<body>
<table id="mytable">
<tr>
<th>Name</th>
<th>City</th>
</tr>
<tr>
<td>XML</td>
<td>London</td>
</tr>
<tr>
<td>HTML</td>
<td>New York</td>
</tr>
<tr>
<td>CSS</td>
<td>Paris</td>
</tr>
</table>
<p>
This is a test.
</p>
<table id="othertable">
<tr>
<th>Name</th>
<th>City</th>
</tr>
<tr>
<td>Java</td>
<td>Boston</td>
</tr>
<tr>
<td>CSS3</td>
<td>Paris</td>
</tr>
<tr>
<td>HTML5</td>
<td>Paris</td>
</tr>
</table>
</body>
</html>
The code above defined two simple tables, each of which defines the id attribute.
The ID selector selects the table with the id value of mytable
and
then selects the td
elements that it contains.
It is not selecting direct descendants.
It skips the tr
elements to select the td
elements.
Example 3
<html>
<head>
<style type='text/css'>
body {<!-- w ww. j av a 2s .c o m-->
font-face: sans-serif;
}
h1 {
margin: 5px;
}
p {
border: 1px solid rgb(200, 200, 200);
background: rgb(234, 234, 234);
padding: 5px;
margin: 5px;
}
p.note {
background: yellow;
border: 1px solid gold;
}
span.code {
font-family: monospace;
padding: 0 10px;
}
p span.code {
background: yellow;
}
p.note span.code {
background: lightyellow;
}
</style>
</head>
<body>
<p>
Descendant selectors apply styles based on ancestral relationships. <span
class='code'><span></span> element named <em>code</em>, which
is a descendant of <span class='code'><p></span> elements. To do
this, the selector <span class='code'>p span.code</span> is used.
</p>
<p class='note'>
The note text is given different styles. To do this another descendant
selector is used. This time the selector is <span class='code'>p.note
span.code</span>
</p>
</body>
</html>