I'm running into an issue with text wrapping inside of flexbox. I want the flex item to always be the width of the wrapped text, so an icon next to the item will stick next to the text. Instead, the text wrapping causes a gap between the text and the icon.
This is an example of the problem:
.flex-container {
display: flex;
flex-direction: row;
width: 100%;
flex-wrap: nowrap;
justify-content: space-between;
}
.flex-item {
display: flex;
flex-grow: 0;
}
.flex-item__description {
background: yellow;
}
.flex-item__icon {
background: orange;
}
<p>Works Ok at full width:</p>
<div class="flex-container">
<div class="flex-item">
<span class="flex-item__description">Affordable long-term quintessential media</span>
<span class="flex-item__icon"></span>
</div>
<div class="flex-item">
<span class="flex-item__description">Other</span>
<span class="flex-item__icon"></span>
</div>
</div>
<p>But once the container gets small enough so the text starts wrapping, the icon is no longer aligned next to the text. There's a bunch of empty yellow space.</p>
<div class="flex-container" style="max-width: 290px">
<div class="flex-item">
<span class="flex-item__description">Affordable long-term quintessential media</span>
<span class="flex-item__icon"></span>
</div>
<div class="flex-item">
<span class="flex-item__description">Other</span>
<span class="flex-item__icon"></span>
</div>
</div>
This is what I want it to look like when it's necessary for the text to wrap due to the container's width being reduced. In this case, the item should fit the text width.
Otherwise, when there's enough room for all of the text to be on one line, it should display on one line.
Does anyone have an idea how to solve this problem? Flexbox or not? I'm looking for a generalized responsive solution that works on all screen sizes, that does not use Javascript. The icon should always fit to the right of the text inside the item it's assocated with, without wrapping to a new line.