Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I vertically center text in a dynamically height div?

<body>     <div style="position:absolute; height:100%; width:100%;">         <h1 style="text-align:center;">Text</h1>     </div> </body> 

How can I vertically center the h1 tag inside of the div tag, no matter how tall the div element is? i.e. If the user changes his browser height, I want the h1 to vertically align in the center, according to the new height.

Thanks.

like image 588
Albion Avatar asked Jun 07 '12 20:06

Albion


People also ask

How do I center text vertically in a div?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

How do I center text vertically in line-height?

Use line-height for vertical centering with a fixed height To vertically center a single line of text or an icon within its container, we can use the line-height property. This property controls the height of a line in a run of text and adds an equal amount of space above and below the line-box of inline elements.

How do I center text vertically and div horizontally?

For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.


1 Answers

The best solution I've ever encountered is to make use of the display property and set the wrapper element as a table to allow the usage of vertical-align:middle on the element to be centered:

See this working Fiddle Example!

HTML

<body>     <div>         <h1>Text</h1>     </div> </body> 

CSS

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; } 

TESTED ON

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)
like image 200
Zuul Avatar answered Oct 06 '22 00:10

Zuul