DEV Community

Cover image for How to center a div in 2024
Kasra Madadipouya
Kasra Madadipouya

Posted on

How to center a div in 2024

Centering a div has long been a meme among software developers, particularly backend developers like me, who often struggle with frontend technologies, including CSS.

The good news is that the struggle is finally over, thanks to the new align-content CSS property. Of course, this property handles vertical alignment only. More on that later.

How it was done historically

Before the introduction of align-content, we usually had to use either CSS Grid or Flexbox to achieve vertical alignment.

Grid example:

<div style="display: grid; align-content: center; justify-content: center; height: 100vh;">
    Hello World!
</div>
Enter fullscreen mode Exit fullscreen mode

Flexbox example:

<div style="display: flex; flex-direction: row; align-items: center; justify-content: center; height: 100vh;">
    Hello World!
</div>
Enter fullscreen mode Exit fullscreen mode

The justify-content property is used for the horizontal alignment of div content in both Grid and Flexbox. For a regular div, we can simply use text-align as follows:

<div style="text-align: center; height: 100vh;">
    Hello World!
</div>
Enter fullscreen mode Exit fullscreen mode

How it is done in 2024

With the introduction of align-content, no longer need to rely on Grid and Flexbox, each of which has some drawbacks. We can achieve the same result more cleanly with the following:

<div style="align-content: center; height: 100vh;">
    Hello World!
</div>
Enter fullscreen mode Exit fullscreen mode

As mentioned earlier, this only handles vertical alignment. For horizontal alignment, we can still use the reliable text-align property in combination with align-content.

<div style="align-content: center; text-align: center; height: 100vh;">
    Hello World!
</div>
Enter fullscreen mode Exit fullscreen mode

Please note that the minimum supported browser versions are Chrome 123, Firefox 125, and Safari 17.4

Resources

Featured images credits

  • Featured image generated by ChatGPT

Top comments (0)