Flexbox is a great way of building simple and not-so-simple content layouts. Whether you are building a card with various content elements or trying to put together a page with a list of items, Flexbox is a friendly alternative to CSS floats.
This week, I ran into a nice tutorial in which I learned that using margin: auto can help you align flex items. Let’s take a look at a couple of examples of how we can use this trick.
Say you are styling a simple navigation which is a short list of items such as Home, About, Blog, Contact and Login. Normally it wouldn’t make sense to align the Login link together with the rest of the navigation items. A more common approach is to move the login link to the far right of the page. There are many ways to achieve this but if you are already using Flexbox to layout the navigation, moving your login link to the far right only takes a line of css code. See the attached codepen for an example:
The navigation is a nice trick to align link items. Now let’s do a more complex example. One which I personally had problems with and thanks to margin auto I was able to resolve without hacking or using absolute position. You’ll see what I mean in a moment.
Take a look at the example of these two cards:
Nothing wrong with them. But what if you wanted to move the “Learn More” link to the bottom of the card so that they always align regardless of how much content each card has? As with anything, there are more than one way to achieve this, but if you are already using Flexbox for the cards, lining up the Learn more link only takes one line of CSS; what do you think that line of css looks like? You guessed it: margin-top: auto.
Look at the very last line in the above codepen. Feel free to toggle it on and off to see how this affects the alignment of the Learn more link.
I kind of lied when I said it only takes one line of css to make this happen. Actually the markup structure and knowing where to use Flexbox is critical for this to work. The pen shows you all you need to make this work.