I am trying to make all sibling flex items the same width as the one with the longest text, without making its text wrap. So if an item has the text "First" and another one has much longer text, the two should still have the same width without making the longer one wrap its text. If this is not possible with just CSS and you may have a React solution, I’m all ears. Thanks!
<div class="container">
<div class="item">First </div>
<div class="item">Second thing is long </div>
<div class="item">Third is </div>
<div class="item">Fourth is even longer and longer </div>
<div class="item">Fifth </div>
<div class="item">Sixth </div>
</div>
.container {
width: 800px;
display: flex;
background: blue;
overflow: auto; //it's okay if the items overflow and scroll
flex-wrap: nowrap;
height: 130px;
}
.item {
margin: 10px;
background: red; // the color here is to make it easier to see if all the items are the same width
flex-shrink: 0;
display: flex;
flex-wrap: nowrap;
flex-basis: calc(100% / 6); //the number 6 here will be dynamic, but it will always be the number of items in the container
}
2
Answers
White space doesn’t allow the text to move in second line and overflow will allow scroll in whichever child text will be larger than its width
So here is something you are trying to achieve and here is a sample code to help
html code
css code
output image
Just a brief explanation of the css properties i used
flex: 1 1 auto;
on .item makes all items grow equally based on the longest one.white-space: nowrap;
ensures that the text inside .item does not wrap.::before
pseudo-element tricks the flex container into considering the natural width of the longest itemthe ::before has a flex: 1 1 0 rule, making the container adapt its width based on the longest item, which then forces all items to match the same width.
then this rule
visibility: hidden
ensures this pseudo-element doesn’t appear visually but still takes part in layout calculations.