25

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:

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?

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

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
John Stimac
  • 5,040
  • 6
  • 35
  • 58
  • possible duplicate of [Div width 100% minus fixed amount of pixels](http://stackoverflow.com/questions/651317/div-width-100-minus-fixed-amount-of-pixels) – Gajus Apr 06 '14 at 13:15

4 Answers4

25

use calc() to calculate the intended width:

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

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

Michael
  • 5,458
  • 3
  • 19
  • 18
13

By CSS rules, the width property 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 and some additional space be allocated for margins. This inevitably causes horizontal scrolling.

As a workaround, you can wrap the table inside a div element and set margin on it.

Jukka K. Korpela
  • 178,198
  • 33
  • 241
  • 350
4

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.

table
{
    border-collapse:collapse;
    padding:20px;
    margin:0;
    width:100%;
}
Victor
  • 49
  • 1
  • 1
2

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 style="margin">
  <table style="width:100%">
  </table>
</div>
LucasJohn
  • 31
  • 4