Reputation: 203
I would need to know how can I place elements to center while still maintaining the justify-content: space-between
attribute?
Roughly something like this:
The red items need to be aligned with justify-content: space-between
so they would "touch" the black lines. If there if only one item on the line, it would be aligned to center.
Upvotes: 6
Views: 3596
Reputation: 373
.flexbox {
display: flex;
flex-direction: column;
justify-content: center;
}
.flex-item {
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-between;
margin:20px 0;
}
.item {
height: 75px;
width: 150px;
background-color: pink;
}
.item:only-child {
margin: 0 auto;
}
<div class="flexbox">
<div class="flex-item">
<div class="item"></div>
<div class="item"></div>
</div>
<div class="flex-item">
<div class="item"></div>
</div>
</div>
Upvotes: 0
Reputation: 6180
You can use flex-basis: calc(50% - x)
where x is half the distance between every two elements in the same row, then use margin:auto
on the last element if it is the only element in that row (i.e. if it is the last element and has an odd order). I am using 20px auto 0px auto
so that I don't override the top margin I have set in the previous rule.
.flex {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.flex div {
flex-basis: calc(50% - 50px);
height: 100px;
margin-top: 50px;
background: #D85E5E;
}
.flex div:last-child:nth-child(odd) {
margin: 50px auto 0px auto;
}
<div class="flex">
<div></div>
<div></div>
<div></div>
</div>
Upvotes: 1