I have a row flexbox with these requirements:
- The flexbox has two child flex items
- The flex items ALWAYS have the same width
- As soon as the container becomes small enough that ANY of the flex items cannot fit their content, cause the flexbox to wrap.
<code><div class="container">
<div class="item">LOOOOOOOOOOONG</div>
<div class="item">SHORT</div>
</div>
</code>
<code><div class="container">
<div class="item">LOOOOOOOOOOONG</div>
<div class="item">SHORT</div>
</div>
</code>
<div class="container">
<div class="item">LOOOOOOOOOOONG</div>
<div class="item">SHORT</div>
</div>
<code>* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
background: lightcyan;
width: 90%;
margin: 20px auto;
display: flex;
flex-flow: row wrap;
gap: 20px;
padding: 20px;
}
.item {
background: salmon;
padding: 10px;
flex: 1 0 0;
overflow: hidden;
}
</code>
<code>* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
background: lightcyan;
width: 90%;
margin: 20px auto;
display: flex;
flex-flow: row wrap;
gap: 20px;
padding: 20px;
}
.item {
background: salmon;
padding: 10px;
flex: 1 0 0;
overflow: hidden;
}
</code>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
background: lightcyan;
width: 90%;
margin: 20px auto;
display: flex;
flex-flow: row wrap;
gap: 20px;
padding: 20px;
}
.item {
background: salmon;
padding: 10px;
flex: 1 0 0;
overflow: hidden;
}
As you can see screenshot, the flexbox never wraps.
4
It’s not possible to easily do what you want to do. The only way would be to use Javascript to check the actual content length and adjust the layout accordingly.
If you can estimate the length of your content, you can get close using display: grid
with grid-template-columns: repeat(auto-fit, minmax(width_of_your_widest_child, 1fr))
.
Read more
<code>* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
background: lightcyan;
width: 90%;
margin: 20px auto;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
gap: 20px;
padding: 20px;
}
.item {
background: salmon;
padding: 10px;
}</code>
<code>* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
background: lightcyan;
width: 90%;
margin: 20px auto;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
gap: 20px;
padding: 20px;
}
.item {
background: salmon;
padding: 10px;
}</code>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
background: lightcyan;
width: 90%;
margin: 20px auto;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
gap: 20px;
padding: 20px;
}
.item {
background: salmon;
padding: 10px;
}
<code><div class="container">
<div class="item">LOOOOOOOOOOONG</div>
<div class="item">SHORT</div>
</div></code>
<code><div class="container">
<div class="item">LOOOOOOOOOOONG</div>
<div class="item">SHORT</div>
</div></code>
<div class="container">
<div class="item">LOOOOOOOOOOONG</div>
<div class="item">SHORT</div>
</div>