Pages

Tuesday, 18 December 2012

What is CSS Inheritance and Why Should I Use CSS Inheritance?

What is CSS Inheritance and Why Should I Use CSS Inheritance?

Concept of CSS Inheritance

Inheritance in CSS (Cascading Style Sheets) code is different from the inheritance in OOPS (Object Oriented Programming). In CSS Inheritance, the child div or class inherits the properties of parent div or class.

Example of CSS Inheritance

Concept of CSS Inheritance can be better understood by following example:

Consider the following HTML code:

<div class="Parent">
  <p class="Child">
    Example of CSS Inheritance
  </p>
</div>

Now, consider the CSS code below:

.Parent
{
  background-color: yellow;
  color: green;
}
.Child
{
  background-color: inherit;
  color: inherit;
  font-weight: normal;
}

By examining the above HTML and CSS code, we can understand that parent div has background-color css property as yellow and color css property as green. In the child element, we are inheriting the background and color property, so the background and color css property of child class will also be yellow and green respectively.

Why to use CSS Inheritance?

CSS Inheritance reduces your css code size, makes your css code easily readable and maintainable.

Suppose you have a parent element which has multiple child elements and all these elements have same font. Now there are two ways to do your css code:

CSS code without Inheritance

#parent p {font-family: arial}
#parent li {font-family: arial}
#parent h2 {font-family: arial}
#parent a {font-family: arial}

In above example, the parent element has multiple child elements like p, li, h2, a etc. and each having the same font family. Now by using CSS Inheritance, you can code like this

CSS code with Inheritance

#parent {font-family: arial}

Same font will be applied to all your child elements and no need to mention the font family for each child element explicitly.

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.