CSS inheritance

Understand the meaning and importance of CSS inheritance

When you set certain properties on a selector in CSS, the properties will be inherited by all children of the selector.

I saidsome, Because not all properties show this behavior.

This happens because certain properties can be inherited. This helps us write CSS more concisely, because we don't have to explicitly set this property again on every child node.

Some other attribute pairsIs notBe inherited.

Think about fonts: you don’t need to applyfont-familyGo to each tab of the page. You setbodyMark the font, each child will inherit it, as well as other attributes.

Thisbackground-colorOn the other hand, inheriting property has little meaning.

Inherited properties

This is a list of properties that can be inherited. This list is not comprehensive, but these rules are just the most popular rules you might use:

  • border-collapse
  • border-spacing
  • caption-side
  • color
  • cursor
  • direction
  • empty-cells
  • font-family
  • font-size
  • font-style
  • font-variant
  • font-weight
  • font-size-adjust
  • font-stretch
  • font
  • letter-spacing
  • line-height
  • list-style-image
  • list-style-position
  • list-style-type
  • list-style
  • orphans
  • quotes
  • tab-size
  • text-align
  • text-align-last
  • text-decoration-color
  • text-indent
  • text-justify
  • text-shadow
  • text-transform
  • visibility
  • white-space
  • widows
  • word-break
  • word-spacing

I got it from hereNice Sitepoint articleAbout CSS inheritance.

Mandatory attribute inheritance

What if you have a property that is not inherited by default and want to inherit that property in children?

In the child, set the attribute value to a special keywordinherit.


body {
	background-color: yellow;

p { background-color: inherit; }

Mandatory property not inherited

Instead, you may have inherited a property, and you want to avoid inheritance.

you can use itrevertRestore its keywords. In this case, the value will revert to the original value provided by the browser in its default style sheet.

In practice, this is rarely used, and in most cases, you will set another value for the property to override the inherited value.

Other special values

apart frominheritwithrevertFor the special keywords we just saw, you can also set any attribute to:

  • initial: Use the default browser style sheet (if any). If it is not, and the attribute is inherited by default, the value is inherited. Otherwise do nothing.
  • unset: If the attribute is inherited by default, it is inherited. Otherwise do nothing.

Download mine for freeCSS Manual

More CSS tutorials: