Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS table td width - fixed, not flexible

I have a table and I want to set a fixed width of 30px on the td's. the problem is that when the text in the td is too long, the td is stretched out wider than 30px. Overflow:hidden doesn't work either on the td's, I need some way of hiding the overflowing text and keeping the td width 30px.

<table cellpadding="0" cellspacing="0">     <tr>         <td>first</td><td>second</td><td>third</td><td>forth</td>     </tr>     <tr>         <td>first</td><td>this is really long</td><td>third</td><td>forth</td>     </tr> </table> 
like image 984
Richard Westington Avatar asked Jul 12 '11 02:07

Richard Westington


People also ask

How do you set the fixed width of a TD table?

By using CSS, the styling of HTML elements is easy to modify. To fix the width of td tag the nth-child CSS is used to set the property of specific columns(determined by the value of n) in each row of the table.

How do you force td width?

The width of the columns i.e. td in a table can be fixed very easily. This can be done by adding the width attribute in the <td> tag. If the width is not specified, the width of the column changes according to the change in the content. The specifications of width for the columns can be in pixels, or percentage.

How do I restrict table width in CSS?

The best possible solution for this is the one you are using now. Since you cannot predict the number of columns you cannot set a width to each column. So setting the overflow of the parent div to auto and the child table width to 100% is the best solution.


1 Answers

It's not the prettiest CSS, but I got this to work:

table td {     width: 30px;     overflow: hidden;     display: inline-block;     white-space: nowrap; } 

Examples, with and without ellipses:

body {      font-size: 12px;      font-family: Tahoma, Helvetica, sans-serif;  }    table {      border: 1px solid #555;      border-width: 0 0 1px 1px;  }  table td {      border: 1px solid #555;      border-width: 1px 1px 0 0;  }    /* What you need: */  table td {      width: 30px;      overflow: hidden;      display: inline-block;      white-space: nowrap;  }    table.with-ellipsis td {         text-overflow: ellipsis;  }
<table cellpadding="2" cellspacing="0">      <tr>          <td>first</td><td>second</td><td>third</td><td>forth</td>      </tr>      <tr>          <td>first</td><td>this is really long</td><td>third</td><td>forth</td>      </tr>  </table>    <br />    <table class="with-ellipsis" cellpadding="2" cellspacing="0">      <tr>          <td>first</td><td>second</td><td>third</td><td>forth</td>      </tr>      <tr>          <td>first</td><td>this is really long</td><td>third</td><td>forth</td>      </tr>  </table>
like image 67
Cᴏʀʏ Avatar answered Nov 03 '22 02:11

Cᴏʀʏ