CSS Inheritance

CSS Inheritance
Nikhil
Published on 2021-07-09 05:10:06

Automatic inheritance


Inheritance the a fundamental mechanism of CSS by which the computed values of some properties of an element are applied to its' children. This is particularly useful when you want to set a global style to your elements rather than having to set said properties to each and every element in your markup.

Common properties that are automatically inherited are: font, color, text-align, line-height.

Assume the following stylesheet:

#myContainer {
color: red;
padding: 5px;
}

This will apply color: red not only to the <div> element but also to the <h3> and <p> elements. However, due to the nature of padding its value will not be inherited to those elements.

<div id="myContainer">
<h3>Some header</h3>
<p>Some paragraph</p>
</div>

 

Enforced inheritance


Some properties are not automatically inherited from an element down to its' children. This is because those properties are typically desired to be unique to the element (or selection of elements) to which the property is applied to. Common such properties are margin, padding, background, display, etc.

However, sometimes inheritance is desired anyway. To achieve this, we can apply the inherit value to the property that should be inherited. The inherit value can be applied to any CSS property and any HTML element.

Assume the following stylesheet:

#myContainer {
color: red;
padding: 5px;
}
#myContainer p {
padding: inherit;
}

This will apply color: red to both the <h3> and <p> elements due to the inheritance nature of the color property. However, the <p> element will also inherit the padding value from its' parent because this was specified.

<div id="myContainer">
<h3>Some header</h3>
<p>Some paragraph</p>
</div>

ATutorialHub Related Guide

Comments (8)

Leave a Comment

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

User Comments

html tutorial comments

panduranga gupta

2021-07-05 07:03:13

good website for learning and help me a lot

html tutorial comments

raju

2021-09-25 14:58:47

The awsome website i am looking like for a long time, good work atutorialhub team keep doing

html tutorial comments

Shivani

2021-09-01 15:03:56

Learning a lot from the courses present on atutorialhub. The courses are very well explained. Great experience

html tutorial comments

Harshitha

2021-09-10 15:05:45

It is very helpful to students and easy to learn the concepts

html tutorial comments

Sowmya

2021-09-14 15:06:41

Great job Tutorials are easy to understand Please make use of it

html tutorial comments

Zain Khan

2021-09-18 15:07:23

Great content and customized courses.

html tutorial comments

Rudrakshi Bhatt

2021-09-09 15:08:10

Well structured coursed and explained really well!

html tutorial comments

Pavana Somashekar

2021-09-11 15:09:08

Good platform for beginners and learn a lot on this website