Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 224
John Stimac Avatar asked Jan 11 '12 00:01

John Stimac


People also ask

How do I make a full width table in HTML?

You need to set the margin of the body to 0 for the table to stretch the full width. Alternatively, you can set the margin of the table to a negative number as well.

How do you add margins to a table in HTML?

What you could do is : wrap table in a div tag. add margin to div. set table width to 100%

Does Max Width include margin?

This property sets the maximum content width of a block or a replaced element. This maximum width does not include padding, borders, or margins.

Does width 100% include padding?

No, element width does not include padding, margin, or border. The basic difference between padding and width is that in padding you define the space around the element and on the other hand in the width you define the space of the element. Property Used: width: This property is used to define the size of the element.


2 Answers

use calc() to calculate the intended width:

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

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

like image 59
Michael Avatar answered Sep 23 '22 18:09

Michael


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.

like image 21
Jukka K. Korpela Avatar answered Sep 23 '22 18:09

Jukka K. Korpela