Home  >  Article  >  Web Front-end  >  How to center a div in 4

How to center a div in 4

王林
王林Original
2024-09-05 06:32:02744browse

How to center a div in 4

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>

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>

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>

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

Resources

  • MDN Web Docs: align-content
  • Build Your Own: CSS Vertical Center

Featured images credits

  • Featured image generated by ChatGPT

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn