Chris Coyier over at css-tricks.com had a great example of a css conundrum: how to centre, both vertically and horizontally, multiple lines of text. He some good code (using table-cell) but his code for IE relied on some (script)expressions which can have the unfortunate habbit of slowing down a page.
[update: to get a bit more background on absolute & relative positioning, and how to center horizontally, read: On Horizontal CSS Centering using Absolute Positioning or how Relative Positioning can rock your css.]
The regular way of vertically centring in css has been documented by Dušan Janovský back in 2004. It needs an extra div for its IE solution, but it doesn’t require any expressions, only regular (fast!) css. Because a div-tag is semantically empty (like the span-tag), it doesn’t add any wrong semantic meaning (like a table-tag would).
The .area
div isn’t stricly necessary, but it was in the original problem posed in the css-tricks.com article. I have however edited out the superfluous background declaration, as it doesn’t have anything to do with positioning.
I’ve updated the example to use conditional comments instead of hacks. The html (in your page) becomes:
<div class="area" id="two">
<div class="bubble">
<div>
<p>Doing this may not be as easy or obvious as we would hope.</p>
</div>
</div>
</div>
The css (in your stylesheet) becomes:
.area {width:300px; height:300px; position:relative; float:left; }
.bubble {position:absolute; left:93px; top:21px; width:135px; height:84px; display:table; }
.bubble div {display:table-cell; vertical-align:middle; text-align:center;}
The IE specific css (in your html-page) becomes:
<!--[if lt IE 8]>
<style>
.bubble div {position:absolute; top:50%;}
.bubble div p {position:relative; top:-50%}
</style>
<![endif]–>
Have a look at the demo to see what you should end up with. Questions welcome!
3 replies on “Vertically centring in css (without hacks and multi-line enabled)”
I did not want to use absolute positioning, so I did the following:
.videoPost div{
position: relative;
top: 25%;
height: 25%;
}
inspired by the above blog post. Probably the same technique. Thanks for the info!
Why would you not want to use absolute positioning?
I’ve heard this before, and I don’t know where it comes from, but there’s seemingly some kind of scare-mongering going on…
[…] Update: read how to do it vertically in: vertically centring in css (without hacks and multi-line enabled) […]