Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 3 CSS SELECTORS AND INHERITANCE

Inheritance


Problem You want to style an element and have all its descendants be styled the same.


Solution


CSS is designed so that many properties are inherited by default. This means you can
assign one of these inherited properties to any element, and any descendants will
inherit the property. Most inline properties are inherited by default. A list of all
properties and how they are inherited follows.

Pattern


Inheritance is a type of selector that is built into the CSS language. You do not have to
do anything to use inheritance. When a browser encounters an inherited property, it
automatically selects descendant inline elements and applies its rule to them. When
you assign a property directly to an element, it overrides any inherited value.

Inherited properties


The following properties are inherited by all elements:
visibility and cursor
The following properties are inherited by inline elements:
letter-spacing, word-spacing, white-space, line-height, color, font, font-family,
font-size, font-style, font-variant, font-weight,
text-decoration, text-transform, and direction
The following properties are inherited by terminal block elements:
text-indent and text-align
The following properties are inherited by list elements:
list-style, list-style-type, list-style-position, and list-style-image
The following property is inherited by table elements:
border-collapse

Noninherited


The following properties are not inherited:
display, margin, border, padding, background, height, min-height, max-height,
width, min-width, max-width, overflow, position, left, right, top, bottom, z-index,
float, clear, table-layout, vertical-align, page-break-after, page-break-before,
and unicode-bidi

Limitations


CSS provides a constant value named inherited that you can assign to any property.
When you assign inherited to a property, that property inherits its value from its
parent element. This allows you to force properties to inherit. Internet Explorer
versions 7 and earlier do not implement inherit. The following tip shows how you can
simulate inheritance for any property.

Tip


You can simulate inheritance for properties that cannot inherit. You first select a
starting element using any selector. You then follow the selector by the descendant
operator and the universal selector. The pattern is SELECTOR *. For example, you can
put a border around all elements descended from <html> by using html * {
border:1px solid black; }. I often use this code to see the nesting of all elements in
a document.

Related to Position and Group Selectors

Free download pdf