1

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>

<!-- End of parent tag. -->
</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?

2
  • 2
    It's the default behaviour of all display:block elements to stretch as far as the parent container allows, yes. Commented Sep 29, 2013 at 20:27
  • here is an easy test, where the width is not set for the parent: jsfiddle.net/crazytonyi/XxNnu/2 Commented Sep 29, 2013 at 20:36

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, block level elements will expand to the width that the parent will let them (width minus padding).

Edit: if you want the child to only be as width as it contents, add display: inline-block to it (also check here).

Comments

0

Yes, the div is by default a block element. And because you didn't specify width its value is "auto". This means that the browser calculates the width and normally that's 100% of the width of the parent element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.