【问题标题】:How to align 2 tables (left and center) inside a div?如何在 div 中对齐 2 个表格(左和中)?
【发布时间】:2017-11-08 12:00:33
【问题描述】:

我想在一个 div 中居中一个表格,并让另一个表格浮动在第一个表格的左侧。 我想要的结果是这样的:

[(左表)(中心表)]

但是使用我当前的 HTML 和 CSS(见下文)我得到了这个结果:

[(左表)(中心表)]

这里的问题是它使第一个表向左浮动,而第二个表在剩余空间中居中。

这是代码:

#wrapper {
  text-align: center;
  width: 500px;
  border: 1px solid black;
}

#left {
  float:left;
}

#center {
  margin: 0 auto;
}

td {
  border: 1px solid black;
  width: 100px;
}
<div id="wrapper">
  <table id="left">
    <tr>
      <td>
        Left
      </td>
    </tr>
  </table>

  <table id="center">
    <tr>
      <td>
        Center
      </td>
    </tr>
  </table>
</div>

关于如何修复它的任何帮助?

【问题讨论】:

    标签: html css alignment


    【解决方案1】:

    尝试position:absolute; left:0px; 用于第一个表,position:relative; 用于包装器

    body{
        margin:0px;
        padding:0px;
    }
    
    #wrapper {
        text-align: center;
        border:1px solid #ddd;
        position:relative;
       
    }
    #left {
        position:absolute;
        left:0px;
        /*
        float:left;*/
    }
    #center {
        margin: 0 auto;
        
    }
    <div id="wrapper">
        <table id="left" border="1">
          <tr>
            <td>table1</td>
          </tr>
        </table>
        <table id="center" border="1">
          <tr>
            <td>table2</td>
          </tr>
        </table>
    </div>

    【讨论】:

    • 谢谢!这很完美。一直在寻找这个。
    【解决方案2】:

    .table-container {
      float: left;
      position: relative;
      width: 100%;
    }
    table {
      float: left;
      width: 100px;
      border:1px solid #ddd;
    }
    .tbl2 {
      position: absolute;
      top: 0;
      left: calc(50% - 50px);
    }
    <div class='table-container'>
      <table class='tbl1'>
        <td> Hello </td>
      </table>
      <table class='tbl2'>
        <td> Hello </td>
      </table>
    </div>

    【讨论】:

    • 请附上一些信息,说明问题是什么以及您如何解决问题。
    • 由于您必须在左侧设置一个表格,在中间设置另一个表格,因此您必须将至少一个表格位置设置为绝对位置。所以,我设置了第二张表(中间一张)的绝对位置,将其左侧位置设置为 calc(50% - 50px)
    【解决方案3】:

    尝试将#wrapper 设置为position: relative;#left 设置为position: absolute; left: 0;

    #wrapper {
      text-align: center;
      background-color: skyblue;
      text-align: left;
      position: relative;
    }
    table {
      border: 1px solid black;
    }
    #left {
      background-color: red;
      position: absolute;
      left: 0;
    }
    #center {
      background-color: yellow;
      margin: 0 auto;
    }
    <div id="wrapper">
      <table id="left">
        <tr>
          <td>Left Table</td>
        </tr>
      </table>
      <table id="center">
        <tr>
          <td>Center Table</td>
        </tr>
      </table>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      相关资源
      最近更新 更多