Search code examples
htmlcsshtml-tablealignment

How to align a table within a TD?


I have a table with 2 <tr> and 2 <td>:

<table>
    <tr>
        <td>
            <table>
                <!-- other content -->
            </table>
        </td>
        <td/>
    </tr>
    <tr>
        <td/><td/>
    </tr>
</table>

Where the ***** is I need to insert pretty much the same table (which does not contain another table). but when I debug it the table is left aligned.

Live Example

I want that the table in the upper left box is right aligned (for knowledge: and center aligned).

For example: The table within is 32px width but the containing td is 64px width.

How can I align the table to the right?


Solution

  • A table is a block-element; text-align and align only works on inline-elements. So for a block-element you have to use margin:

    CSS:

    .centered{
        margin: 0 auto;
    }
    
    .rightaligned{
        margin-right: 0;
        margin-left: auto;
    }
    
    .leftaligned{
        margin-left: 0;
        margin-right: auto;
    }
    

    HTML:

    <td>
        <table class="leftaligned">
            <!-- Other Content -->
        </table>
        <table class="centered">
            <!-- Other Content -->
        </table>
        <table class="rightaligned">
            <!-- Other Content -->
        </table>
    </td>
    

    This will work in almost every browser, even Internet Explorer 7.