Two HTML tables side by side, centered on the page

前端 未结 10 1596
小蘑菇
小蘑菇 2020-12-25 12:10

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

相关标签:
10条回答
  • If it was me - I would do with the table something like this:

    <style type="text/css" media="screen">
      table {
        border: 1px solid black;
        float: left;
        width: 148px;
      }
      
      #table_container {
        width: 300px;
        margin: 0 auto;
      }
    </style>
    
    <div id="table_container">
      <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>
      <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>

    0 讨论(0)
  • 2020-12-25 12:28

    Off the top of my head, you might try using the "margin: 0 auto" for #outer rather than #inner.

    I often add background-color to my DIVs to see how they're laying out on the view. That might be a good way to diagnose what's going onn here.

    0 讨论(0)
  • 2020-12-25 12:30

    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.

    0 讨论(0)
  • 2020-12-25 12:36

    The problem is that you need to give #inner a set width (anything but auto or inherit). The margin: 0 auto; trick only works if the inner element is narrower than its container element. Without being given a width, #inner is automatically expanding to the full width of #outer, which causes its contents to be flush left.

    0 讨论(0)
提交回复
热议问题