HTML table full width with margin

csshtmlhtml-table

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/

Best Answer

use calc() to calculate the intended width:

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

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