Inheritance in CSS properties

Here, In this example I have two divisions where one is nested within another. I’m calling the outer division a parent and the division which is nested a child.

CSS

/* for parent div tag*/
#parent{
  width: 500px;
  height: 300px;
  z-index: 1;
  background-color: #CCC;
  border:thin solid black;
  margin:25px;
  padding:20px;
}


/* for child div tag */
#child{
  border:thin solid #F00;
  height:50px;
  background-color:#FFC;
}

HTML

<!-- Start of parent tag -->
<div id="parent">
  <p> This is parent div tag. </p>
<!-- Child div tag -->
<div id="child">
  <p> This is child div tag. </p>
</div>

It looks like this in the web browser:

enter image description here

My question is: How does the child div tag gets the size of it’s width? Is it because of inheritance from the parent div tag or is it just by default behavior that it will expand up to the parent div container if you don’t specify a width?


solution

Width cannot be inherited. What you are seeing is default behavior.

See the specs on block level elements

“Each block-level element generates a principal block-level box that contains descendant boxes and generated content and is also the box involved in any positioning scheme.” – W3C

By default, block elements have a width of 100%. That means that if a width isn’t specified, it will be 100% of the parent.

In this case, the parent’s width is 542px.

The calculation is based on width:500px; + padding-left:20px;+ padding-right:20px; +border 2px;

enter image description here

The child’s width is exactly 500px. (100% of the parents width - minus padding/border).

enter image description here

jsFiddle here You can play around with it and inspect the elements.