DEV Community

loading...
Cover image for Horizontally and Vertically Centering in CSS

Horizontally and Vertically Centering in CSS

Mike S
Software Developer at GameGlass
・1 min read

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. 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. 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 :)

Discussion (10)

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
hummersi profile image
sagi hammer

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
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
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
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
yannickvdthoren profile image
Yannick Vandenthoren

What you can also do is just put a margin: auto on the element you want to center. ;)

Collapse
skhmt profile image
Mike S Author • Edited

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