Inheritance
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> <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>
- 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:
body { color: blue; } h1 { color: green; }
- Save.
- In the browser, you should see the following:
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
- Try adding a
div
selector to thecss
and making the color red.
Video and Code References
Questions? Subscribe and ask in the video comments: