Table layout sucks… but I do miss valign

With margin: 0 auto; it’s pretty easy to center content horizontally, but it’s a pain without tables to center content vertically inside either a container or the window. Here’s a pretty simple CSS method I found. In this example, we’ll be centering in the browser window, but this can be applied inside a container as well.

The trick with this approach is that the container and the centered element must have some height set. Apart from this drawback, this method seems to work great across browsers and is fantastically simple. Enjoy.

The HTML

<html>

    <body>

        <div id=”distance”></div>

        <div id=”centered_element”>

            Here’s some centered content for you.

        </div>

    </body>

</html>

The CSS

html, body

{

height:100%; /* Height must be set on the container for proper centering. */

}

#distance

{

height:50%;

margin-bottom:-9px; /* Half of centered element’s height */

}

#centered_element

{

margin: 0 auto;

width: 200px;

height:18px;

}

This entry was posted in Web. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">