Robin has covered this before, but I’ve heard some confusion about it in the past few weeks and saw another person take a stab at explaining it, and I wanted to join the party.
Say you have a flex container with some flex items inside that don’t fill the whole area.
See the Pen
ZEYLVEX by Chris Coyier (@chriscoyier)
on CodePen.
Now I want to push that “Menu” item to the far right. That’s where auto margins come in. If I put a margin-left: auto;
on it, it’ll push as far away as it possibly can on that row.
See the Pen
WNbRLbG by Chris Coyier (@chriscoyier)
on CodePen.
Actually, you might consider margin-inline-start: auto;
instead and start using logical properties everywhere so that you’re all set should you need to change direction.
See the Pen
gObgZpb by Chris Coyier (@chriscoyier)
on CodePen.
Also, note that auto margins work in both directions as long as there is room to push. In this example, it’s not alignment that is moving the menu down, it’s an auto margin.
See the Pen
XWJpobE by Chris Coyier (@chriscoyier)
on CodePen.
An interesting special case is when multiple flex children have ‘auto’ margins — the remaining space is evenly distributed between them.
Try an example with four children, where the third child has
margin-left: auto
and the fourth child hasmargin-left: auto
andmargin-right: auto
.Or an example with four children, where the third child has both
margin-left: auto
andmargin-right: auto
— the result is the third child centered in the remaining space, with the fourth child pushed to the end of the inline box according to theflex-direction
.I’m new to flexbox but this really makes sense to me
Looking at the example you gave, it seems to work the same way as
justify-content: space-between;
Can this be used in place of it?This! Used it on a 4 Column Blog Layout, so that all 4 Columns appear with the same height.
Do you have any guidance on deciding when to use this method versus using alignment properties? (
align-self: flex-end
, for instance)In my basic demo, it does the same thing!