How to Vertically Center Text in a Resizable Div?

Barbara Streisand
Release: 2024-11-09 07:50:02
Original
250 people have browsed it

How to Vertically Center Text in a Resizable Div?

How to Vertically Center Text in a Resizable Div

When working with dynamically sized div elements, it can be challenging to maintain vertical alignment of text within the div. This issue arises when the height of the div is not fixed, as it can vary depending on factors such as user browser height.

Solution:

To address this problem, a versatile solution involves utilizing the display property to transform the div element into a tabular structure. By setting the display property to table, we create a table-like environment within the div. This allows us to use the vertical-align property on the text element to center it vertically within the div.

HTML Markup:

<body>
    <div>
        <h1>Text</h1>
    </div>
</body>
Copy after login

CSS Styling:

body {
    width: 100%;
    height: 100%;
}

div {
    position: absolute;
    height: 100%;
    width: 100%;
    display: table;
}

h1 {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
Copy after login

Notable Browsers Tested:

Using this technique, we have successfully tested the vertical centering of text in div elements in various browsers, including:

Windows XP:

  • Internet Explorer 8
  • Opera 11.62
  • Firefox 3.6.16
  • Safari 5.1.2
  • Google Chrome 18

Windows 7:

  • Internet Explorer 9
  • Opera 11.62
  • Firefox 12
  • Safari 5.1.4
  • Google Chrome 18

Linux Ubuntu 12.04:

  • Firefox 12
  • Chromium 18

The above is the detailed content of How to Vertically Center Text in a Resizable Div?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template