Tuesday, September 25, 2012

Centering content in a DIV element

Centering contents of a DIV element

No this isn't exactly brain surgery but it did stump me for a spell. I laid out a div with a width of 100% and a text-align:center, then I dropped in a table with 2 columns and a fixed width.

The desired results was a table centered in the page. Unfortunately that was not the case. I'm not sure why this didn't work, hopefully someone can shed some light on it for me.

Here's the code I tried:


<div style="text-align:centerwidth:400px;">
        <table border="0" cellpadding="0" cellspacing="0" width="400">
            <tr>
                <td>fdsdf
                </td>
            </tr>
        </table>
    </div>

By simply adding the margin: auto; attribute to the table, it magically moves to the center of the div as desired.


 <table border="0" cellpadding="0" cellspacing="0" width="400" style="margin:auto;">


If anyone has a reason behind this I would like to hear it. Just one of those weird quirks that makes me go hmmm... Could be by design, just seems wonky. I also dropped some controls in the DIV and it didn't center them either.  Hmmm.

Happy Coding...
Merlin

No comments:

Post a Comment