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.
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>
Flexbox example:
<div style="display: flex; flex-direction: row; align-items: center; justify-content: center; height: 100vh;"> Hello World! </div>
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>
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>
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>
Please note that the minimum supported browser versions are Chrome 123, Firefox 125, and Safari 17.4
The above is the detailed content of How to center a div in 4. For more information, please follow other related articles on the PHP Chinese website!