- A Short History of Style for the Web
- What Is CSS?
- How Is CSS Used?
- Basic CSS Syntax
- The Basics of Selectors
- Basic Properties: Font Styles
- Inheritance
- Getting Specific: class and id Selectors
- Common Text Layout Properties
- Combinators: Descendant and Child Selectors
- Common Background Properties
- Dynamic Selectors
- Basic Page Layout
- Advanced Page Layout
- Positioning
- Advanced Selectors
- Display Types
- More Properties
- Media Types
- Importing Style Sheets
- Quality Assurance
- Specific Challenges and Techniques
Inheritance
If we were to set for example a font-weight on the body element using, say, this statement:
body { font-weight: bold } |
then all of the text in paragraphs, headings, and other elements would be bold. But why? What's going on?
Many, though not all, CSS properties are inherited by child elements from their parent elements. For example, font-weight is inherited. This means that all descendants of the body—that is, every visible element in the document—will have a font-weight of bold as well, unless some other CSS statement specifies that its font-weight should be normal.
Inheritance is powerful and sometimes confusing, but without it, CSS would be much less efficient. We'd have to specify font-size, font-weight, color, line-height, and many other properties for every single type of element in a document, which would produce larger and more difficult to maintain CSS files. I won't exhaustively list the properties that are inherited and those that aren't (these are detailed in the CSS specification). The good news is that in almost every case, properties that we'd want to be inherited will be, and those that we wouldn't want to be inherited—border and padding, for example—aren't.
In addition, we can always use a special keyword inherit for any CSS property, which specifies that the value should be inherited from the parent element, regardless of whether the property is inherited by default.