If you're anything like me, vertically and horizontally centering an HTML element has been the bane of your existence at some point in your career.
Luckily, this solution works in every browser, even IE 11:
display: flex;
justify-content: center;
align-items: center;
justify-content
is for horizontal alignment by default. Removing it or setting justify-content: flex-start;
places the child element on the left. Setting justify-content: flex-end;
places the child element on the right.
align-items
is for vertical alignment by default. Removing it or setting align-items: flex-start;
places the child element at the top. Setting align-items: flex-end;
places the child element at the bottom.
Here's an example.
You can probably stop using padding
, absolute
left/right and top/bottom positioning, float
, line-height
, transform
, and any other tricks :)
Top comments (9)
Keep in mind that
align-items
&justify-content
switch between horizontal/vertical alignment based on theflex-direction
value (default isrow
).I understand this and still can never get flexbox to work the way I want it to. I just have such a block in actually making flexbox work for me.
I pretty religiously reference back to this CSS-Tricks Article: css-tricks.com/snippets/css/a-guid...
Same
These 2 resources helped me alot with Flexbox:
This one is from FreeCodeCamp.
This one is just a Code Pen Playground for Flexbox so you can see it in action.
Hope that helps.
Great tip!
The direction of flex-start / end actually depends on the direction of the document.
For example in rtl languages flex end is actually at the left.
My heart sinks when I realize I need to vertically center an HTML element. I'll def be referencing this in the future.
I'm a big fan of flexbox. I remember having to do these weird workarounds to center things. It has definitely made my life easier!
Funny story, I didn't realize someone else also wrote a short article about flexbox earlier today π