Child Selector

Exercise

  1. 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>
  1. Save.
  2. If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
  3. In the "styles.css" file, replace the code with the following:
#div1 p {
  background: green;
  color: white;
}

#div2 > p {
  background: blue;
}
  1. Save.
  2. In the browser, you should see the following:

  3. Exercise 2 Result

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


Video and Code References


Questions? Subscribe and ask in the video comments:


GitHub and Other References