Tutorial :How to define cell width for 2 HTML tables with different column counts?



Question:

If I have 2 tables:

<table id="Table1">      <tr>          <td></td><td></td><td></td>      </tr>  </table>    <table id="Table2">      <tr>          <td></td><td></td><td></td><td></td>      </tr>  </table>  

The first has 3 columns, the second has 4 columns.

How can I define a style to represent both tables when I want Table1's cell width to be 1/3 the width of the full table, and Table2's cells are 1/4 the width of the table?

edit: To clarify after a comment in one of the answers below that suggests to set the table width to 100%, the text in some columns will exceed the natural division width.


Solution:1

The answers so far have got close, but none quite right:

#Table1, #Table2 {      width: 100%;      table-layout: fixed;  }  

and that's all.

table-layout: fixed is to be preferred for all tables where column widths shouldn't depend on cell contents. This is faster and much more reliable than the default auto table layout algorithm.

Because none of the columns have an explicit width here (either from a <col> element or from the first row of <td>​s, they all share the remaining 100% of available width equally between them, however many there are. So you don't have to calculate 25%s or 33%s.


Solution:2

Using some CSS:

#Table1 td{      width: 33%;  }  #Table2 td{      width: 25%;  }  


Solution:3

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html xmlns="http://www.w3.org/1999/xhtml" >        <style type="text/css">          table           {              table-layout: fixed;              width: 100%;          }      </style>  


Solution:4

Try using the following CSS:

.table1 td {width:33%}  .table2 td {width:25%}  


Solution:5

This CSS should work

table td{      width:100%;  }    table{      table-layout:fixed;  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »