DEV Community

Cover image for Horizontally and Vertically Centering in CSS
Mike
Mike

Posted on • Edited on

Horizontally and Vertically Centering in CSS

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;
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
jackharner profile image
Jack Harner πŸš€

Keep in mind that align-items & justify-content switch between horizontal/vertical alignment based on the flex-direction value (default is row).

Collapse
 
ben profile image
Ben Halpern

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.

Collapse
 
jackharner profile image
Jack Harner πŸš€

I pretty religiously reference back to this CSS-Tricks Article: css-tricks.com/snippets/css/a-guid...

Collapse
 
iam_timsmith profile image
Tim Smith

Same

Collapse
 
androidninjax profile image
TJ • Edited
Collapse
 
hammersi profile image
Sagi h

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.

Collapse
 
andrewbrooks profile image
Andrew Brooks πŸ‘¨β€πŸ’»

My heart sinks when I realize I need to vertically center an HTML element. I'll def be referencing this in the future.

Collapse
 
iam_timsmith profile image
Tim Smith

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!

Collapse
 
skhmt profile image
Mike • Edited

Funny story, I didn't realize someone else also wrote a short article about flexbox earlier today πŸ˜‚