When I use flexbox, if I want a margin to add spacing to each element I would usually do this:
.flexbox-item {
flex: 1 0 auto;
margin-right:10px;
}
.flexbox-item:last-of-type {
margin-right: 0px;
}
This works if I don't use flex-wrap because they last item will always be the actual last item on the row.
When I use flex-wrap however, the last item of the row changes depending on the window width (and more rows are added automatically), meaning I'm removing the right margin from the 1st item in a row sometimes.
Anyone know of a solution to this issue?
EDIT: I don't believe this is a duplicate
This is about keeping rows horizontally equal, not vertically.
Anyway, my solution is using negative margins which can found on that thread by digging through it but it's not the most popular solution. Here's my solution:
Seems that the answer to this issue is to add a negative margin to the parent flexbox container.
.flexbox-container {
margin-right:-10px;
}
.flexbox-item {
flex: 1 0 auto;
margin-right:10px;
}
Then when your flexbox items change to 100%, just remove the right margin from the items:
@media (max-width: 767px) {
.flexbox-item {
margin-right:0px;
}
.flexbox-container {
margin-right: 0px;
}
}
If there is a better solution I'm all ears.
Therefore you could use margin-top: auto to distribute the space between the other elements and the last element. This will position the last element at the bottom. Likewise, you can also use margin-left: auto or margin-right: auto for the same alignment horizontally.
Setting the margin property on a flex child will push the child away from that direction. Set margin-left to auto , the child will push right. Set margin-top to auto and the child will push to the bottom.
You need to add align-content: flex-start on flex-container or in your case #wrapper element. Save this answer. Show activity on this post. In a multi-line flex row layout, the align-content controls how the flex items aligns vertical when they wrap, and since its default is stretch , this is expected behavior.
I'm not entirely sure about your use-case. But why not use justify-content: space-between
instead of margin
. Then you don't need to remove margin for the last element in the row.
https://jsfiddle.net/n2vqwg79/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With