DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Cover image for Horizontally and Vertically Centering in CSS
Mike
Mike

Posted on • Updated 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 (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
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
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 on
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 Author • Edited on

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

๐ŸŒš Browsing with dark mode makes you a better developer.

It's a scientific fact.