Friday, May 15, 2009

Centering Box Elements in HTML with CSS

Most of my carreer I have been a "backend" guy, working on the database, and building services for consumption by other systems. Over the last couple of years I have had the pleasure of becoming a "frontend" guy, working on various web sites.

So far the site I have been working on only targets IE, As such there hasn't been a strong motiviation to add support for Firefox; however, with IE8 being much more standards compliant, I have a personal desire to get the site to a point where I can turn off IE7 Compatability Mode.

Today I was a little stumped when I was working on markup simillar to the following:


    <div style="text-align: center">

        <table>

            <tr>

                <td>

                    I am Centered

                </td>

            </tr>

        </table>

    </div>



In IE8 with Compatability mode this renders as I expect. The table is centered within the div; however, in Firefox and IE8 standard mode the table is left aligned.

I've always questioned why am I using text-align to align elements, but it always worked so I just shrugged and moved on. Turns out IE wasn't honoring that text-align should only align text. It was using to align all elements. The proper way to do this is:


    <div>  

        <table style="margin-left:auto;margin-right:auto">

            <tr>

                <td>

                    I am Centered

                </td>

            </tr>

        </table>

    </div>




This is so much better. I hated having to use text-align center, and then go through and set all the text up so it would align back left. I have tested this in Firefox 3.0.7 and IE8 (IE7 and Standards Mode). It feels to good finally learn the right way to do something.

1 comment:

vitamin b said...
This comment has been removed by a blog administrator.