The solution to fit child div to it’s parent is to simply not declare width: 100%
.
The default is width: auto
, which for block-level elements (such as div
), will take the “full space” available anyway (different to how width: 100%
does it).
Just in case it’s not already clear from my answer: just don’t set a width
on the child div
.
You might instead be interested in box-sizing: border-box
.
HTML
<div id="parent">
<div id="child2">
Hi! 50px of padding, and it's working!
</div>
</div>
CSS
#parent {
border: 3px solid #f0f
}
#child2 {
padding: 50px;
background: cyan;
}