Question

What happens when margin: auto is used on a flex item?

#css #flexbox

Answer

It happens that the side of the flex item where the margin is applied (left, right, or both) takes up any available space, effectively overriding the container's justify-content.

So, similarly to how align-self can override align-items on the cross axis, auto margins can override justify-content on the main axis.

This can be used, for example, to space flex items evenly along the main axis inside of a row (using justify-content: space-between on the container) with the last item floating all the way to the right side (using margin-left: auto on that flex item).

[^1]: Understanding Flexbox: Everything you need to know > Auto-margin Alignment
[^2]: Flexbox’s Best-Kept Secret

Learn

Author

xavi

Reviews
Last
next

Students 1