I want to have a parent container shrink to fit the contents of its children. This I’ve found is doable with either inline-block or inline-flex. I also want the children to be able to expand to a max-width, regardless of their content, which is where I’m having a problem.
It seems the two conditions are in conflict, as the child will not expand to the max-width in any scenario I try unless its contents allow it to. I simply want the child to take the maximum width it can and have the parent adjust accordingly.
Here’s a fiddle with what I’m going for: https://jsfiddle.net/handcraft4/t857qyb4/39/
.red-wrapper {
display: flex;
flex-direction: column;
align-items: center;
container-type: inline-size;
container-name: page-wrapper;
padding: 20px;
border: 1px solid red;
}
.blue-header {
border: 1px solid blue;
text-align: center;
}
/* this style is set inside the component that will load here */
.green-dynamic-content {
max-width: 500px; /* should be 500 but it is not */
border: 1px solid green;
padding: 5px;
}
.orange-footer {
border: 1px solid orange;
text-align: right;
}
<div class="red-wrapper">
<div class="black-content">
<div class="blue-header">
Header
</div>
<!-- begin component w. style -->
<div class="green-dynamic-content">
Width set by component
</div>
<!-- end load component -->
<div class="orange-footer">
Footer
</div>
</div>
</div>
Does anyone have any suggestions?
2
Answers
.red-wrapper
hasalign-items: center
which makes.black-content
a centered flex item, so it won’t grow unless you explicitly set its width, give italign-self: stretch
or give its parentalign-items: stretch
(which is the default value).I should also mention that
align-self: center
does not have an effect on.green-dynamic-content
since its parent.black-content
is not a flex container.To achieve the desired layout of children expanding to the maximum width possible, remove
align-items: center
from.red-wrapper
. To center.green-dynamic-content
, give itmargin-inline: auto
.Here’s the updated CSS:
You are using
container
so setwidth: 100cqw
to thegreen-dynamic-content
element and it will do what you want.