How to Align Last Flex Item to Right

Ryan Yu
2 min readMar 25, 2016

--

Few weeks ago I found something interesting with flexbox in W3C and wanted to share it with you.

I presume you know what flexbox is and how cool it is. I won’t go into details about that but if you want to find out more about flexbox, check this link out:
http://tympanus.net/codrops/css_reference/flexbox/

and play here:
http://the-echoplex.net/flexyboxes/

Have you ever wondered how you can put only the last flex item to the right but keep all other items still left?

Something like this:

Let’s check out the func spec for flexbox on W3C, especially this section:
https://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#auto-margins

The magic happens with the auto margin. Especially pay closer attention to this line:

Prior to alignment via ‘justify-content’ and ‘align-self’, any positive free space is distributed to auto margins in that dimension.

So if you assign the auto value to the margin property, the positive free space will be taken up.

Let’s see the screenshot below without any margin set.

You will see the free space at the right side of the last flex item.

And if you apply margin-left: auto to the last item, the positive free space will be taken up to the left dimension and the last flex item will be pushed to the right.

Awesome right? It is very good if you wanted to put the last menu item to the right.

You can apply the auto value to any directions of margin like left, right, top or bottom.

And I am sure that you now know what would happen if we apply margin: auto to the second flex item :)

As always, if you have any questions, please leave your comments.

If you want to learn awesome front-end skills and boost your front-end career, please join us at FrontEnd30.com today 👍

--

--

Ryan Yu

Lead UI engineer • Writer, Speaker • UI animation, Canvas, SVG, Three.js, PixiJS, WebGL, Shaders • React, CSS (SEM+BIO), A11y