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

How to center a div in 4

王林
Release: 2024-09-05 06:32:02
Original
759 people have browsed it

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>
Copy after login

Flexbox example:

<div style="display: flex; flex-direction: row; align-items: center; justify-content: center; height: 100vh;">
    Hello World!
</div>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:dev.to
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template