How can I vertically center text in a dynamically height div?
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)
In 2012, the accepted answer was the correct/best option.
Flash forward 8 years, and flex boxes are supported by every mainstream browser (IE10+):
display: flex;
align-items: center;
flex-direction: column; /* To also center horizontally, change to `rows` or remove */
Note: If you care about IE10, you need to include -ms-
prefix versions, per my hyperlink above.
I have the easiest 3 lines of css which are going to blow your mind and you will be thinking "Why didn't I think of this initially". Use this on the element you would like to be positioned vertically centered and the parent container just add a height of 100%.
position: relative;
top: 50%;
transform: translateY(-50%);
The position can be either relative, absolute or fixed.
The answer I find the least obtrusive and least confusing requires inserting a <span>
tag before the <h1>
element: http://jsfiddle.net/Wexcode/axRxE/
HTML:
<div>
<span></span><h1>Text</h1>
</div>
CSS:
div { text-align: center; /* horizontally center */ }
div span {
height: 100%;
vertical-align: middle;
display: inline-block; }
div h1 {
vertical-align: middle;
display: inline-block; }
Expanding this technique to vertically-align to the browser-height: http://jsfiddle.net/Wexcode/axRxE/1/