How can I make an HTML table 100% wide and all its cells will be only width than their contents?

I have this grid:

enter image description here

If I change the width of the tables from 100% to auto, the table breaks horizontally.

enter image description here

This is undesirable. How to make table columns (td elements) automatically shrink to fit their contents, while at the same time the table and tr elements fill the entire space of their parent?

+4
source share
2 answers

How can I make table columns (td elements) automatically shrink to fit their contents, while at the same time the table and tr elements fill the entire space of my parent?

Items

<table> and <tr> are as wide as the <td> elements inside them. You cannot have each <td> as small as its contents, and have the table as a whole as wide as the available space, because the table can only be wider than the cells inside it.

(i.e., unlike most HTML elements, <table > elements cannot be independent of their contents.)

You can set one cell as wide as possible by assigning it a width of 100% :

 <table style="width: 100%; background: grey; color: white;"> <tr> <td style="background: red;">Content</td> <td style="background: green;">Content</td> <td style="background: blue; width: 100%;">Content</td> </tr> </table> 

See http://jsfiddle.net/9bp9g/

+7
source

The width of the <td> will be determined by the width of the <td> at the beginning of the <tr> .

Otherwise, you can use CSS to define rules for <td> width, for example:

 .myform tr td{padding:0px;margin:0px;} .myform td{width:200px;} 
+1
source

All Articles