November 28, 2012

Understanding Inheritance in CSS


Inheritance in CSS

Mostly CSS style that is applied to an element is also inherited to its descendants. Just like humans inherit skin color, height, baldness etc... from their parents and grandparents. In this post, lets try to understand why certain styles are inherited and why some or not.

Why elements are inherited?

why_inheritance_is_applied_in_CSS

Because, inheritance is big time saver. Imagine a webpage containing thousands of elements which needs to be styled, and to style them individually is a heck to work. It is only because of this inheritance property in CSS, we save a lot of time.

Let us see an example to understand this,


<!-- this is HTML -->
<p>The journey is difficult, long, sometimes <strong>impossible</strong>. Even so, I know few 
people who have let these <em>difficulties stop them</em>. We enter the world without
<em>knowing for sure</em> what happened in the past, what <em>consequences</em> this has 
brought us, and what <em>the future may</em> have in store for us.</p>


/* this is CSS */
p {
   color: #069;
   background-color: yellow;
   padding: yellow;
}

You can see in the above code, the color of the paragraph tag(p) is changed. But, the color property is also inherited to its descendant selectors like strong and em's. Imagine if there is no inheritance then we need to style each and every element in a webpage.

Limits of Inheritance

Some CSS properties do not inherit their values on to their descendant elements for good,

  • Properties that affect the placement of elements on the page like margins, padding, background color, borders of elements are not inherited.
  • Every browsers have their own default property style for some elements. Elements like headings, anchor links have their own predefined styles like have bigger font-size or coloring the link to blue etc...
  • Some times multiple styles conflict to apply style to a single element. In those cases, it depends on certain inheritance rules.

No comments:

Post a Comment