Absolutely, it is possible to achieve this by utilizing inline-flex
instead of flex
, allowing the container to expand with its child elements.
The reason behind the flex parent not automatically growing with its child using flex
is because it behaves like a block-level element, which does not exceed the dimensions of its parent, whereas inline elements do.
As illustrated, the main parent
element, whether with or without min-width: 100%
, does not expand to fit its contents with flex
, unlike inline-flex
or even inline-block
would.
However, the content of the parent
still overflows and affects its layout as though it were expanding, triggering the appearance of scrollbars on the outer container.
The slight disparity in width between the parent
and parent
with min-width
is due to the exclusion of padding
from the specified width. Rectifying this can be done by applying box-sizing: border-box;
to ensure consistency in width.
For reference, here is a sample code snippet:
.parent {
padding: 20px;
background: yellow;
}
.parent.with-min-width {
min-width: 100%;
}
.flex {
display: inline-flex;
flex-direction: column;
background-color: red;
padding: 20px;
}
.flex .item {
width: 800px;
padding: 20px;
background-color: blue;
}
<div class="parent">
<div class="flex">
<div class="item">
</div>
</div>
</div>
<div class="parent with-min-width">
<div class="flex">
<div class="item">
</div>
</div>
</div>