Descendent Selector
Exercise
- In the "index.html" file, replace the code with the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS</title> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <div class="container"> <h1 id="section-one">Section 1</h1> <p>This is the first paragraph of section <span class="number">1</span></p> </div> <div class="container"> <h1 id="section-two">Section 2</h1> <p class="green">This is the first paragraph of section <span class="number">2</span></p> </div> <div class="container"> <h1 id="section-three">Section 3</h1> <p>This is the first paragraph of section <span class="number">3</span></p> </div> <p>Not in the container</p> </body> </html>
- Save.
- If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
- In the "styles.css" file, replace the code with the following:
.number { color: orange; } #section-one { color: grey; } #section-two { color: blue; } #section-three { color: green; } .container p { color: darkblue; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
.container p { color: darkblue; }
A descendant selector in CSS is used to select elements that are descendants of a particular parent element.
The
selector allows you to target an element that is inside another element, no matter how deep it is in the HTML
document. The syntax for a descendant selector uses a space between the two selectors. Notice in the resulting
web
page that the first three <p>
texts are dark blue but the last <p>
text is
default color. The last <p>
element is not within a <div>
element with the
"container" class.
Experiment with the Code
- Try adding a selector for a
span
that is the descendant of ap
to thecss
and making thefont-weight
set tobold
.
Video and Code References
Questions? Subscribe and ask in the video comments: