Two HTML tables side by side, centered on the page

dland picture dland · Dec 6, 2008 · Viewed 103.9k times · Source

I have two tables on a page that I want to display side by side, and then center them within the page (actually within another div, but this is the simplest I could come up with):

<style>
  #outer { text-align: center; }
  #inner { text-align: left; margin: 0 auto; }
  .t { float: left; }
  table { border: 1px solid black; }
  #clearit { clear: left; }
</style>

<div id="outer">
  <p>Two tables, side by side, centered together within the page.</p>

  <div id="inner">
    <div class="t">
      <table>
        <tr><th>a</th><th>b</th></tr>
        <tr><td>1</td><td>2</td></tr>
        <tr><td>4</td><td>9</td></tr>
        <tr><td>16</td><td>25</td></tr>
      </table>
    </div>

    <div class="t">
      <table>
        <tr><th>a</th><th>b</th><th>c</th></tr>
        <tr><td>1</td><td>2</td><td>2</td></tr>
        <tr><td>3</td><td>5</td><td>15</td></tr>
        <tr><td>8</td><td>13</td><td>104</td></tr>
      </table>
    </div>

  </div>
  <div id="clearit">all done.</div>
</div>

I understand that it's something to do with the fact that the tables are floated, but I'm at a loss as to understand what I'm missing. There are many web pages that describe something like the technique I show here, but in any event it doesn't work; the tables cling stubbornly to the left hand margin.

Answer

dland picture dland · Dec 7, 2008

Unfortunately, all of these solutions rely on specifying a fixed width. Since the tables are generated dynamically (statistical results pulled from a database), the width can not be known in advance.

The desired result can be achieved by wrapping the two tables within another table:

<table align="center"><tr><td>
//code for table on the left
</td><td>
//code for table on the right
</td></tr></table>

and the result is a perfectly centered pair of tables that responds fluidly to arbitrary widths and page (re)sizes (and the align="center" table attribute could be hoisted out into an outer div with margin autos).

I conclude that there are some layouts that can only be achieved with tables.