Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the table column width constant regardless of the amount of text in its cells?

In my table I set the width of the first cell in a column to be 100px.
However, when the text in one of the cell in this column is too long, the width of the column becomes more than 100px. How could I disable this expansion?

like image 282
Misha Moroshko Avatar asked Dec 16 '10 04:12

Misha Moroshko


People also ask

How do you set column width in a table?

To change the width to a specific measurement, click a cell in the column that you want to resize. On the Layout tab, in the Cell Size group, click in the Table Column Width box, and then specify the options you want.

How do I keep my column width fixed in HTML?

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 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.


2 Answers

I played with it for a bit because I had trouble figuring it out.

You need to set the cell width (either th or td worked, I set both) AND set the table-layout to fixed. For some reason, the cell width seems to only stay fixed if the table width is set, too (I think that's silly but whatev).

Also, it is useful to set the overflow property to hidden to prevent any extra text from coming out of the table.

You should make sure to leave all of the bordering and sizing for CSS, too.

Ok so here's what I have:

table {    border: 1px solid black;    table-layout: fixed;    width: 200px;  }    th,  td {    border: 1px solid black;    width: 100px;    overflow: hidden;  }
<table>    <tr>      <th>header 1</th>      <th>header 234567895678657</th>    </tr>    <tr>      <td>data asdfasdfasdfasdfasdf</td>      <td>data 2</td>    </tr>  </table>

Here it is in JSFiddle

This guy had a similar problem: Table cell widths - fixing width, wrapping/truncating long words

like image 100
ptpaterson Avatar answered Sep 21 '22 21:09

ptpaterson


See: http://www.html5-tutorials.org/tables/changing-column-width/

After the table tag, use the col element. you don't need a closing tag.

For example, if you had three columns:

<table>   <colgroup>     <col style="width:40%">     <col style="width:30%">     <col style="width:30%">   </colgroup>     <tbody>     ...   </tbody> </table> 
like image 33
Hyathin Avatar answered Sep 21 '22 21:09

Hyathin