Skip to main content
CodeNerd-stream

Double-tagging, or CSS vertical align

By May 22, 2012No Comments

This is pretty geeky, but I’ve tried several ways of doing this, and wanted to post what I’ve found to be the best. And based on testing, it’s also the most cross-browser compliant solution.

The issue is (seemingly) simple. How do you use the equivalent of valign=”middle” in CSS? With tables this was pretty simple. But we’ve all moved on from tables for layout. I hope.

While CSS (including CSS3) does have a vertical-align, you can’t use it in the same way for you text-align for example. You can’t simply tell it that all text within a container should sit halfway down the div.

The way I’ve found most useful is to double-tag. That is, to use a parent div, and then a child within it.

Here’s the code to show what I mean:
#content1 {
display:table;
height:400px;
}

#content2 {
display:table-cell;
vertical-align:middle;
}

And then when writing the HTML:
<div id=”content1″>
<div id=”content2″>
This text will sit halfway down the div, regardless of whether I have one line of text, or three.
</div>
</div>

In essence the first div says “Go on, act like I’m a table”.  And then second continues, “And let’s just say I’m a table cell. Because cells *can* have vertical-align assigned to them!”

Double-tagging.

Author Peter

More posts by Peter

Leave a Reply

Exit mobile version