Horizontally and Vertically Centering in CSS
Mike 🐈‍⬛

Mike 🐈‍⬛ @skhmt

About: Software Engineer

Joined:
May 21, 2019

Horizontally and Vertically Centering in CSS

Publish Date: Jul 9 '19
118 10

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

Comments 10 total

  • Mike 🐈‍⬛
    Mike 🐈‍⬛Jul 9, 2019

    Funny story, I didn't realize someone else also wrote a short article about flexbox earlier today 😂

  • Jack Harner 🚀
    Jack Harner 🚀Jul 9, 2019

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

  • Ben Halpern
    Ben HalpernJul 9, 2019

    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.

  • Tim Smith
    Tim SmithJul 10, 2019

    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!

  • Andrew Brooks 👨‍💻
    Andrew Brooks 👨‍💻Jul 10, 2019

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

  • Sagi h
    Sagi hJul 10, 2019

    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.

Add comment