CSS Inheriting style

Posted by admin at April 13, 2020

Part of the reason a well structured HTML document is so important is because HTML elements inherit stylistic properties.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My HTML page</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <header>
      <h1>Title</h1>
      <h2>sub title</h2>
    </header>
    <section>
      <p>This is my paragraph text</p>
      <ul>
        <li>list item 1</li>
        <li>list item 2</li>
        <li>list item 3</li>
      </ul>
    </section>
  </body>
</html>

You can see it’s basic structure from the way I have formatted the tags with tabbing, but here is a more visual representation of the hierarchy of tags. Tags that contain other tags are parents, and the tags inside of them are their children in the following tree representation:

2 4 2 inheritance tree - CSS Inheriting style

Through inheritance, CSS property values set on one element will be transferred down the tree to that element’s children. In this example, every element gets the same font because we applied it to the body tag. Since the body element is a common parent for all visible elements is a convenient selector for when you want to set stylistic rules for the entire document.

Then, we applied different styles at different levels of the tree so that the “li” or list element tag ends up with three different styles (font, underline and green) without us actually applying any style directly to that tag.

body {
  font-family: "Century Gothic", sans-serif;
}
header {
  font-style: italic;
}
section {
  text-decoration: underline;
}
ul {
  color: green;
}

Not every property is inherited, but many are. The CSS specification tell you, for each property, whether it is inheritable. It’s a good idea to keep in mind the structure of your HTML document when choosing your selectors so you can use inheritance to your advantage by applying styles to the top most element and save yourself extra CSS code.

Output:

css intro 2 4 2 - CSS Inheriting style

Comments

Write a Reply or Comment

Your email address will not be published. Required fields are marked *