How to get HTML Table td width to work

It is optional to specify the width of the table or of the td cells. Even if you set the width of the <td> it may not work as you expected because the browser calculates the width in run time based on the contents of the table. Here is the solution to create tables with predictable column widths.

1. Fix the width of the table.

Width can be in percentage as well. But, fix the width of the table first.

table.itemlist
{
  width:80%;
}

2. Set table-layout to ‘fixed’

The table-layout:fixed css property tells the browser that the width of columns in the table is fixed and no need to calculate based on the content.

table.itemlist
{
  width:80%;
  table-layout:fixed;
}

More info on table-layout

3.Set width of the first row of the table

This also means that if you have a heading row, set the width of heading column (th) :

table.itemlist th.descr
{
  width:30%;
}

4.Use overflow: hidden to hide extra text

5. (optional) Use white-space ‘nowrap’

Prevent the text from wrapping using white-space property.

table.itemlist tr td
{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

So here is the complete CSS code:

The CSS code for fixed width table

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

table.fixed-table td
{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/*Don't forget to set the width for td or th (should apply to the first row) */
table.fixed-table td.descr,
table.itemlist th.descr
{
  width:30%;
}

22934

Read more on HTML tables:
HTML table reference and tutorial

Close

Copy and paste this code to display the image on your site

Copied!