DEV Community

Samantha Ming
Samantha Ming

Posted on

Flexbox: Aligning with Auto Margins

Flexbox30 by SamanthaMing.com

Note: This is a shortened repost from my Flexbox30 series. It does assume Flexbox knowledge. So if you're new to Flexbox, I recommend checking it out first (link). And yes, it's a FREE course 😄


Horizontal Alignment with Auto Margins

You learned that align-self gives you control of the child item in the cross axis. Your next question might be "is there something similar for the main axis", say a "justify-self" 🤔 Great question! Unfortunately, the answer is NO 😅. But we have an existing CSS property that we can use! And that's auto margins. We can use it to control the horizontal alignment of a specific element.

Horizontal Alignment with margin-right:auto and margin-left:auto

Vertical Alignment with Auto Margins

Actually, you can also use auto margins to control the vertical alignment of a specific element.

Vertical Alignment with margin-top:auto and margin-bottom:auto

Centering Alignment with Auto Margins

And if you apply all the margins (left, right, top, bottom) with the shorthand margins. You actually center that particular child in the horizontal and vertical direction!

Centering Alignment with margin:auto


Auto Margins Examples

Here are some examples where auto margins really shine! It's great to layout your navbar in whatever style you prefer 🤩

Auto Margins Examples


Which should I use 🤔

I bet your head is spinning now as to use which and when to use what (the problem with choices am I right) 😅. Here's how I go about it:

  1. Always use Flexbox properties
  2. If not possible, use auto margins

Reasoning? I think Flexbox properties are more intuitive and reads more explicit than "auto margins". Check it:

.child {
  align-self: flex-end;
}

vs

.child {
  margin-top: auto;
}

Even if you don't have any Flexbox knowledge. Just be reading this code, you can conclude that the child is aligning to the end. However with the margin-top: auto, you're kinda spinning your head with what that exactly looks like. Of course, this is just my recommendation. You feel free to do what works for you and your team 😊


Flexbox30 Links

Flexbox30: Learn Flexbox in 30 days with 30 code tidbits
Flexbox: Aligning with Auto Margins (Full Version)


Thanks for reading ❤
Say Hello! Instagram | Twitter | Facebook | Blog | SamanthaMing.com

Top comments (2)

Collapse
 
davide profile image
Davide Scarioni

Thank you! I learn something new even today! ;)

Collapse
 
samanthaming profile image
Samantha Ming

Woohoo! Happy to share something new! It’s all about knowledge sharing 😊