Inheritance in CSS - Tutorial
Parent and children.
The content of an HTML page is organized into tags nested within each other, that is to say that the elements are contained in larger elements. The parent is an element that contains others (children).
The drawing below represents a page with an underlined title and a table of 2 lines and 3 columns.
We can represent the elements of this page in these forms, which better highlights the parent/child relationship between them.
Here is how the ties are broken down in this example:
- The body element is the direct parent of two elements: h1 and table.
- table is the direct parent of tbody.
- tbody has two elements tr (the rows of the table).
- Each tr is the direct parent of three cells: td elements.
- Well (you might not have thought of it) but in this case, the h1 element is the direct parent of an element u since the title has been underlined. (1)
- This is not shown in the drawing but the body element has a parent, which is the html element.
(1) Note: the u tag should no longer be used because underlining is a formatting that would rather be defined with CSS.
The concept of inheritance.
When not specified, some properties default to the same value as the parent element. They say they inherit. This avoids having to redefine properties for all child elements. For example the font can be defined at the highest level (the body tag or even html); it will then be useless to define it for all the elements since they will all inherit this value.
This mechanism gave its name to CSS, the C
meaning Cascading
.
We indeed have a cascading inheritance, starting from the highest element, up to all its descendants.
Subtle note: if the inherited value is the result of a calculation, it is that result that is inherited, not the formula that was used to obtain it.
In other words, we do not recalculate a new value with the parameters of the child element; we take the value obtained for
the parent element and that's it.
Here's an example: the character size of the inner frame is inherited from its parent the outer frame, where it is set to 120%.
Both texts are the same size. CSS therefore did not redo a 120% calculation, which would have resulted in larger characters.
It simply took the value found previously.
font-size:120%;
font-size:inherit;
The inherit value.
Some properties do not inherit by default. This is the case for example of background-color
which has an initial value equal to
transparent
.
In these cases, it is still possible to force inheritance by setting the property to inherit
.
Refer to the inherit
value page for more details.
background-color:lightgreen;
transparent
.background-color:inherit;