Inheritance

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>
  <div>
    <h1>Section 1</h1>
    <p>This is the first paragraph of section 1</p>
  </div>
  <div>
    <h1>Section 2</h1>
    <p>This is the first paragraph of section 2</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:
body {
  color: blue;
}

h1 {
  color: green;
}
  1. Save.
  2. In the browser, you should see the following:

  3. Exercise 2 Result

Code Walkthrough and Explanation

Element hierarchy in HTML refers to the parent-child relationship between elements in an HTML document. The parent element is the container for child elements and child elements are nested within the parent element. The structure of the hierarchy affects how the elements are displayed on a web page and how CSS styles are applied.

Inheritance in CSS refers to the process by which certain CSS properties are passed down from parent elements to their child elements. Properties set on a parent element will be inherited by its child elements unless they are explicitly overridden. This helps to simplify CSS code as it eliminates the need to specify the same style multiple times for different elements within a hierarchy.

In the above example, the <body> element is the parent to both the <div> elements and their children so everything on the page inherited the color declaration of blue except for the <h1> elements. The <h1> elements did not inherit the color because there is a separate CSS rule set with the h1 selector that explicitly overrode the color declaration to be green instead.


Experiment with the Code


Video and Code References


Questions? Subscribe and ask in the video comments:



GitHub and Other References