Reputation: 83
I'm in a confusion since yesterday. Actually I have a markup as follows:
<div class="container">
<div class="child>
<div class="descendant">Content</div>
</div>
</div>
And CSS:
.container {
max-width: 500px;
min-width: 100px;
}
The .container
element has some width between 100px
to 500px
according to my content and the child & descendant elements have some other content without any specific width
or min/max-width
.
What happens is that when I apply horizontal padding to .container
, its content-box
size remains as is & just padding
is added to it. But whenever I apply horizontal padding to any of the child or descendant elements, they do not add padding to their size or the parent's size. Instead, their content-box
size reduces and they accommodate padding
.
I seriously can't get what is going on here. Can anyone explain me what's actually happening?
Upvotes: 0
Views: 45
Reputation: 53709
This is just normal box model behavior. Adding padding to an element that isn't bound by a parent element restricting it's size will grow outward to accommodate the new padding. But if an element is contained within a parent with a fixed width, and you add padding to the inner element, it can't grow outward and force the bounding parent to grow - it can only reduce it's content-box
to make room for the padding.
If you want the outer and inner divs to behave consistently, you can add box-sizing: border-box;
to .container
and the padding will not cause the element to grow beyond the specified width/height.
Upvotes: 1
Reputation: 943922
The width describes the content width, which you explicitly set to a maximum of 500px
. So long as there is room, the content width of the container will be 500px
. If you add padding to the container, that doesn't affect the content width because nothing else constrains it.
The descendants, on the other hand, have their width constrained by the container. If you add padding to a descendants, the width is reduced so the whole box can still fit inside teh container.
Upvotes: 2