Home > Web Front-end > CSS Tutorial > How to Vertically Center Text in a Responsive Div Element?

How to Vertically Center Text in a Responsive Div Element?

Patricia Arquette
Release: 2024-11-09 04:20:02
Original
471 people have browsed it

How to Vertically Center Text in a Responsive Div Element?

Vertical Text Alignment in a Responsive Div Element

When dealing with content within dynamically sized DIV containers, aligning text vertically can be challenging. This question explores how to center text vertically within a DIV element regardless of its height.

Problem Statement:

Consider the following HTML structure:

<body>
    <div>
Copy after login

How can the H1 tag be vertically centered within the DIV, regardless of the DIV's height?

Solution:

The most effective solution involves leveraging the display property. By setting the wrapper element as a table, we enable the use of vertical-align:middle to center the element:

<body>
    <div>
        

Text

Copy after login
body {width: 100%; height: 100%;}  /* For visualization purposes */

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

Testing:

The solution has been tested on various platforms and browsers, including:

Windows XP Profissional versão 2002 Service Pack 3

  • Internet Explorer 8.0.6001.18702
  • Opera 11.62
  • Firefox 3.6.16
  • Safari 5.1.2
  • Google Chrome 18.0.1025.168 m

Windows 7 Home Edition Service Pack 1

  • Internet Explorer 9.0.8112.164211C
  • Opera 11.62
  • Firefox 12.0
  • Safari 5.1.4
  • Google Chrome 18.0.1025.168 m

Linux Ubuntu 12.04

  • Firefox 12.0
  • Chromium 18.0.1025.151 (Developer Build 130497 Linux)

The above is the detailed content of How to Vertically Center Text in a Responsive Div Element?. 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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template