带边距的 HTML 表格全宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8812757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:27:34  来源:igfitidea点击:

HTML table full width with margin

htmlcsshtml-table

提问by John Stimac

I have a table:

我有一张桌子:

<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>

and I want it to be as wide as possible while still leaving a 20px margin on each side. So, I did this:

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

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

but it ends up being the width of the parent plus an extra 20px margin on the left, causing a vertical scroll bar to appear. Is there any way to make it 40px less than the parent's width without adding another element to surround it?

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

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

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

回答by Michael

use calc() to calculate the intended width:

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

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

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

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

回答by Jukka K. Korpela

By CSS rules, the widthproperty sets the width of the content of an element, so you are requiring that 100% of the available width be allocated to the table itself andsome additional space be allocated for margins. This inevitably causes horizontal scrolling.

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

As a workaround, you can wrap the table inside a divelement and set marginon it.

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

回答by Victor

You can set a padding on the table-element. The thead, tbody and tfoot and rows within will fill up the space in the table.

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

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

回答by LucasJohn

I found the best answer useful, but it doesn't work in older browsers. What best suited for me was a DIV outside the table setting the margin. Then, the 100% width of the parent would be influenced by this div, not the parent element.

我发现最佳答案很有用,但它在旧浏览器中不起作用。最适合我的是设置边距的表格外的 DIV。然后,父元素的 100% 宽度将受此 div 的影响,而不是父元素。

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