Reputation:
Why is trying to align something in the center of the viewport (or wrapper) either vertically or horizontally (or both) so painful?
I have tried everything I could find in the past hour, from sites like W3Schools to S/O to MSDN - I just don't know how to do it. There has to be an easy way to do this. And WHY can you center a DIV horizontally like this: margin: 0 auto; but not vertically? And why can't you use that same approach with any other element on the page?
I have a one line sentence (testimonial) that i would like to center vertically and horizontally, how can I do this?
Upvotes: 2
Views: 2158
Reputation: 1315
Hey its painful, yes it is. Its stupid that HTML does not by default have these things built in and even in HTML5 one has to use the same hacks. But try these solutions you will less regret to re-invent everything http://intensivstation.ch/en/templates/
Upvotes: 0
Reputation: 1051
Roger Johansson wrote an interesting article about it here: http://www.456bereastreet.com/archive/201103/flexible_height_vertical_centering_with_css_beyond_ie7/
Heres the gist of it:
<body>
<div id="body">
Content goes here
</div>
</body>
With this css:
html, body { width:100%; height:100%; }
html { display:table; }
body {display:table-cell; vertical-align:middle; }
#body { max-width:50em; margin:0 auto; }
Upvotes: 5
Reputation: 42818
This will center both horizontally and vertically and it works in all browsers including IE quirks mode.
div{
width:200px;
height:200px;
background:red;
position:absolute;
left:50%;
top:50%;
margin-left:-100px; /* Negative half the width*/
margin-top:-100px; /* Negative half the height */
}
Upvotes: 4
Reputation: 7032
For centering a line of text, set its CSS line-height
attribute to the same height as the block containing it.
Upvotes: 1