Reputation: 114
I am having a requirement that displaying the dynamic unequal width items in a container but it needs to fulfill the parent container. The item is dynamic so we can not know how long it is. If there is no room in the row, we need to display that item in the next row but the existing rows must be distributed equally to fulfill the container's width. Something like this:
What I did is create a container with display: flex
and put child items inside with their's width fit the content inside. The items can be displayed in the next row if there is no room for it but I have no clue how to distributed existing items to fulfill the whole row?
Code:
.container {
display: flex;
gap: 10px;
flex-wrap: wrap;
width: 350px;
border-style: dotted;
}
.item {
background-color: coral;
padding: 10px 1em;
margin: 5px;
}
<div class="container">
<div class="item">Lorem ipsum</div>
<div class="item">Lorem ipsum dolor</div>
<div class="item">adipiscing</div>
<div class="item">consectetur adipiscing elit</div>
<div class="item">Lorem ipsum dolor sit amet</div>
<div class="item">Lorem ipsum dolor</div>
</div>
I just wonder is there any flexbox's CSS property to solve this problem?
Upvotes: 0
Views: 1021
Reputation: 105873
some extra CSS for the behavior of the content and the children could be used :
flex:1 0 auto;/* make it stretch as much as possible*/
max-width:calc(100% - 10px);/* do not let it be bigger than container width minus margin */
white-space: pre-wrap;/* keep on a single line as much as possible */
Possible demo
* {
box-sizing: border-box;
}
.container {
display: flex;
gap: 10px;/*NOTICE: understood by Firefox at the moment */
flex-wrap: wrap;
width: 350px;
border-style: dotted;
}
.item {
background-color: coral;
padding: 10px 1em;
margin: 5px;
/* update a few behaviors */
flex:1 0 auto;
max-width:calc(100% - 10px);/* 10px is right + left margin */
white-space: pre-wrap;
}
<div class="container">
<div class="item">Lorem ipsum</div>
<div class="item">Lorem ipsum dolor</div>
<div class="item">adipiscing</div>
<div class="item">consectetur adipiscing elit</div>
<div class="item">Lorem ipsum dolor sit amet</div>
<div class="item">Lorem ipsum dolor</div>
<div class="item">Lorem ipsum dolor</div>
<p class="item">Pellentesque habitant morbi tristique senectus et netus et netus et malesuada ac turpis egestas.</p>
</div>
Upvotes: 2