John Stimac
John Stimac

Reputation: 5491

HTML table full width with margin

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/

Upvotes: 27

Views: 29049

Answers (4)

LucasJohn
LucasJohn

Reputation: 41

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>

Upvotes: 2

Michael
Michael

Reputation: 7384

use calc() to calculate the intended width:

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

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

Upvotes: 26

Victor
Victor

Reputation: 45

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%;
}

Upvotes: 2

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201768

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.

Upvotes: 12

Related Questions