Child 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> <h1>Child Selector</h1> <div id="div1"> <div id="div2"> <p>This is a child of div2 but not div1, however, it is a descendent of div1 and div2.</p> </div> <p>This is a descendent of div1.</p> </div> </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:
#div1 p { background: green; color: white; } #div2 > p { background: blue; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
#div2 > p { background: blue; }
A child selector in CSS is used to select all direct child elements of a particular parent element. It is
represented
by the >
symbol and is used to target elements that are immediately nested inside another
element.
In the exercise, the paragraph nested inside the div2
was a child of div2
so only
it's
background color was changed.
Experiment with the Code
- Try adding a
<span>
to one of the<p>
and select it using the child selector method, setting thefont-weight
tobold
.
Video and Code References
Questions? Subscribe and ask in the video comments: