I have a parent flexbox of constrained width (in this example, 500px) with some content, including a child flexbox. I need some flexbox children (ones assigned flex-fill
in the snippet) to fill all available space, but not grow beyond the width allowed by the parent. So the parent element should never be wider than 500px, regardless of any content nested inside.
However, with my current CSS, when the child flexbox has content that is wider than the maximum allowed space, it keeps growing, with no respect to that boundary (despite flex-shrink: 1
and overflow: hidden
). How can this be fixed?
.parent {
width: 500px;
height: 50px;
margin-bottom: 10px;
}
.flex {
display: flex;
flex-direction: row;
}
.flex-fill {
flex-grow: 1;
flex-shrink: 1;
}
.first-level-child {
/* for demonstrating its size easily */
background-color: lightblue;
}
.second-level-child {
/* I was assuming this will clip long text? */
overflow: hidden;
background-color: coral;
}
p {
/* to make sure it has large width */
white-space: nowrap;
}
<div class="parent flex">
<div> <p>Some content</p> </div>
<div class="first-level-child flex flex-fill">
<div class="second-level-child flex-fill">
<!--<p>If short content, all good.</p>-->
<p>If there is very long text here, the first and second level children end up growing. This is not good: the parent div of this text should not care, and always take just the allowed space.</p>
</div>
<div> <p>Other content<p> </div>
</div>
<div> <p> Etc... </p> </div>
</div>
Note: The problem is similar to the one in this question, but the solution doesn’t apply as the content is nested.