Home > Article > Web Front-end > 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>
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; }
Notable Browsers Tested:
Using this technique, we have successfully tested the vertical centering of text in div elements in various browsers, including:
Windows XP:
Windows 7:
Linux Ubuntu 12.04:
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!