Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
HTML表格全宽带边距_Html_Css_Html Table - Fatal编程技术网

HTML表格全宽带边距

HTML表格全宽带边距,html,css,html-table,Html,Css,Html Table,我有一张桌子: <table border=1> <caption>This is a table.</caption> <tr> <th>One</th> <th>Two</th> <th>Three</th> </tr> <tr> <td>Fo

我有一张桌子:

<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>
但它最终是父级的宽度加上左侧额外的20px边距,导致出现一个垂直滚动条。有没有办法让它比父对象的宽度小40px,而不添加其他元素来包围它


jsiddle:

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


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

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

table
{
    border-collapse:collapse;
    padding:20px;
    margin:0;
    width:100%;
}
使用calc()计算预期宽度:

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

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

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


很容易忘记,现在可以使用这些新功能了@MichaelCordingley表示同意,将这种新的CSS功能与旧的模式结合起来似乎并不奇怪(再也不行了?):
<div style="margin">
  <table style="width:100%">
  </table>
</div>