Home  >  Article  >  Web Front-end  >  How to Vertically Center Text in a Div of Unknown Height?

How to Vertically Center Text in a Div of Unknown Height?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 09:52:02724browse

How to Vertically Center Text in a Div of Unknown Height?

Dynamic Vertical Text Alignment in Divs

Achieving vertical text centering within a div of unknown height can be a challenge. Let's delve into a solution that ensures consistent alignment regardless of the div's dimensions.

The solution leverages the display property to set the wrapper element as a table. This allows us to utilize the vertical-align property within the element we want to center.

Example Code:

<body>
    <div>
        <h1>Text</h1>
    </div>
</body>
body {width: 100%; height: 100%;}   /* This is just to "view" the div height... */

div {
    position:absolute; height:100%; width:100%;
    display: table;
}
h1 {
    display: table-cell;
    vertical-align: middle;
    text-align:center;
}

How it Works:

  • The position: absolute and height: 100% properties ensure that the div covers the entire height of the webpage.
  • By setting display: table on the div, we allow the table-cell property on the h1 tag to vertically align its content.
  • The vertical-align: middle property centers the h1 tag vertically within the div. This ensures that the text remains centered even as the div changes size.

This solution has been tested on various browsers and operating systems, including Internet Explorer, Firefox, Chrome, Opera, and Safari. It provides a simple and effective way to vertically center text within a dynamically height div.

The above is the detailed content of How to Vertically Center Text in a Div of Unknown Height?. 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