Reputation: 13
I searched a lot on this forum but my problem is too specific. I would like to achieve this, I try for several months but I can not get work... Thanks in advance if anyone can help me :) :)
I would like to align horizontally 2, 3, 4, 5 or more divs, with variable widths, and with static spacement between each div. And all this must not exceed his parent. So I agree that the 4 div can not do 25% of width, but I do not see how to do ..
Upvotes: 1
Views: 2674
Reputation: 167212
This would be a great use case for flex-box
. I have used the same code for both the cases. The CSS doesn't change, but the HTML does:
.flex-container {
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-flex-wrap: nowrap;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
-webkit-align-content: stretch;
-ms-flex-line-pack: stretch;
align-content: stretch;
-webkit-align-items: flex-start;
-ms-flex-align: start;
align-items: flex-start;
background: #999;
margin: 15px;
padding-right: 5px;
}
.flex-item {
-webkit-order: 0;
-ms-flex-order: 0;
order: 0;
-webkit-flex: 1 0 auto;
-ms-flex: 1 0 auto;
flex: 1 0 auto;
-webkit-align-self: auto;
-ms-flex-item-align: auto;
align-self: auto;
background: #99f;
margin: 5px 0 5px 5px;
}
<div class="flex-container">
<div class="flex-item">Item</div>
<div class="flex-item">Item</div>
<div class="flex-item">Item</div>
</div>
<div class="flex-container">
<div class="flex-item">Item</div>
<div class="flex-item">Item</div>
<div class="flex-item">Item</div>
<div class="flex-item">Item</div>
</div>
You don't need to change the CSS according to the number of sub elements. I have given the example with three and four <div>
s.
Upvotes: 2