【问题标题】:HTML table full width with margin带边距的 HTML 表格全宽
【发布时间】:2012-02-07 10:11:09
【问题描述】:

我有一张桌子:

<table border=1>
    <caption>This is a table.</caption>
    <tr>
        <th>One</th>
        <th>Two</th>
        <th>Three</th>
    </tr>
    <tr>
        <td>Four</td>
        <td>Five</td>
        <td>Six</td>
    </tr>
</table>

我希望它尽可能宽,同时在每边留出 20 像素的边距。所以,我这样做了:

table{
    border-collapse:collapse;
    margin:20px;
    padding:0;
    width:100%;
}

但它最终是父级的宽度加上左侧额外的 20px 边距,导致出现垂直滚动条。有没有办法让它比父宽度小 40px 而不添加另一个元素来包围它?

jsfiddle:http://jsfiddle.net/pvHNM/

【问题讨论】:

标签: html css html-table


【解决方案1】:

根据 CSS 规则,width 属性设置元素内容的宽度,因此您需要将 100% 的可用宽度分配给表格本身一些额外的空间分配给保证金。这不可避免地会导致水平滚动。

作为一种解决方法,您可以将表格包裹在 div 元素中并在其上设置 margin

【讨论】:

    【解决方案2】:

    您可以在表格元素上设置填充。 thead、tbody 和 tfoot 以及其中的行将填满表格中的空间。

    table
    {
        border-collapse:collapse;
        padding:20px;
        margin:0;
        width:100%;
    }
    

    【讨论】:

    【解决方案3】:

    使用 calc() 计算预期宽度:

    table {
        margin: auto;
        width: calc(100% - 40px);
    }
    

    http://jsfiddle.net/EXS76/1/

    【讨论】:

    • 很容易忘记现在可以使用其中一些新功能。 caniuse.com/#search=calc
    • @MichaelCordingley 同意,将这样一个新的 CSS 功能与老派 结合起来确实感觉很奇怪
    【解决方案4】:

    我发现最佳答案很有用,但它不适用于旧版浏览器。最适合我的是设置边距的表格外的 DIV。那么,父元素的 100% 宽度会受到这个 div 的影响,而不是父元素。

    <div style="margin">
      <table style="width:100%">
      </table>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2013-01-21
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多