Reputation: 9184
I can have dynamic amount of child items. I mean 1, 5 or 150 etc in flex container.
How can I set them to be exactly 25%
of flex-basis
so that if I have only 3 items in wrapper: they are still looking like 4 columns, but one is empty.
Example:
https://jsfiddle.net/ybjvtuqg/
<p>
first example
</p>
<div class="items">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
<p>
second example
</p>
<div class="items">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
& style:
.items {
width: 100%;
display: flex;
align-items: center;
justify-content: flex-start;
flex-wrap: wrap;
background: #cecece;
padding: 10px;
margin: 20px;
}
.item {
height: 100%;
flex: 1 0 25%;
margin: 4px;
background: #16B6B6FF;
}
As you can see - in first example it looks like every child takes 33% of width, while I would like to be 25%, and have an empty col in the end with 25% (without changing HTML and do any hardcode).
In the second example: it's the same - on second row items take 50% - that is not correct. Every item should take exactly 25% and leave free space if any...
Is it possible with flex?
Upvotes: 0
Views: 2504
Reputation: 318
Try this
.items {
width: 100%;
display: flex;
align-items: center;
justify-content: flex-start;
flex-wrap: wrap;
background: #cecece;
}
.item {
height: 100%;
margin: 4px;
background: #16B6B6FF;
width: 100%;
max-width: calc(25% - 8px);
}
Upvotes: 1
Reputation: 172
The first solution I just came up with is to change flex-grow
to 0 and flex-basis
to calc(25% - 8px)
.
As follows:
flex: 0 0 calc(25% - 8px);
You have to subtract 8px
because its a sum of margin-left
and margin-right
.
The second solution could be:
<div class="items">
<div class="item__wrapper">
<div class="item">1</div>
</div>
<div class="item__wrapper">
<div class="item">2</div>
</div>
<div class="item__wrapper">
<div class="item">3</div>
</div>
<div class="item__wrapper">
<div class="item">4</div>
</div>
<div class="item__wrapper">
<div class="item">5</div>
</div>
</div>
.item__wrapper {
box-sizing: border-box;
padding: 4px;
flex: 0 0 25%;
}
.item {
height: 100%;
background: #16B6B6FF;
}
Upvotes: 0
Reputation: 14189
You can try this way flex: 0 0 calc(25% - 8px);
8px
its margin
.item {
height: 100%;
flex: 0 0 calc(25% - 8px);
margin: 4px;
background: #16B6B6FF;
}
https://jsfiddle.net/lalji1051/1uhcL76f/5/
Upvotes: 0