Why div1 (blue) is not as wide as div2 (red)?
I always thought that an element is as wide as it’s child by default.
https://codepen.io/jack987/pen/VwJYWEW
.div1 {
background: blue;
height: 200px;
}
.div2 {
background: red;
height: 100px;
width: 4000px;
}
<div class="div1">
<div class="div2">
</div>
</div>
4
Answers
Because
div
as a block element by default is as wide as the containing element. The containing element here isbody
, which is again contained inhtml
, which in turn is as wide as the viewport. Your 4000px wide inner div simply overflows out of the dimension of the outer div.You can change that, by making the outer div
inline-block
, and giving it amin-width
of 100%.The
.div1
has no specified width, so it defaults to the width of its containing block (typically the viewport). This means it won’t automatically expand to accommodate the width of.div2
unless.div2
is content forces it to do so. Since.div2
has a width of4000px
, it overflows.div1
, but.div1
does not expand to fit.div2
.To make
.div1
expand to fit.div2
, you can adddisplay: inline-block;
ordisplay: inline-flex;
in.div1
.Since you haven’t specified a width for div1, it will try to fit its parent container (likely the body or another containing element). It won’t automatically expand beyond the width of its containing block, even if its child is wider.
div2 has an explicit width of 4000px, which is likely wider than the viewport and its parent (div1).
As a result, div2 extends beyond the boundaries of div1, but div1 doesn’t grow to contain it. The red background of div2 will be visible outside of the blue background of div1.
One more thing:
If you set overflow: auto; or overflow-x: auto; on div1, it will create a scrollable container that accommodates the full width of div2.
here you know about positioning in the Css you have to add just absolute position to your parent div and it all done.