Super useful flexbox trick you might not know
Look at this navigation bar for a moment. If you had to implement this with CSS flexbox, how would you do it?
I've seen that a lot of people usually create two elements:
1. First element with the "Brand Name", "Home", "About Us" and "Pricing" links
2. Second one with the "Register" link
And then place them at the two extreme ends using justify-content: space-between
within the flex container.
Something like this:
But, is this the best way to do it? Let's say this is the markup
In this markup, if you use want to create two elements to space them out, you will have to split this list into two lists. Two lists is unnecessary and this might create so many complications later.
The recommended approach
So how do you keep the markup same as above and still achieve the spaced-out appearance using flexbox?
Solution: Auto margins
If you know this, you've unlocked a new level in the game of flexbox.
You can simply make the ul
a flex container and add margin-left: auto
to the Register link item to push the item to the extreme right!
Refer this Codepen link for the demo
Remove the push-right
class and add it to any other li
item and see what happens. That flex item is pushed to the right along with the ones that follow it.
This feature is useful in so many other cases. Look at this card which has a fixed height and needs the button to be placed at the very bottom irrespective of the length of the paragraph.
Do you know how to do this with what you just learnt?
Use flex-direction: column
for the whole card and add margin-top: auto
for the button
.
Try this out on your own and you'll never forget this trick again :) Hope you liked this issue.
📘 Complete Guide to CSS Flex and Grid
If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.