Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the width of a table cell in HTML when it has white-space:nowrap?

I've got a table cell for which I'd like to have the following effects:

width: 100px;
white-space: nowrap;
overflow: hidden;

In other words, the cell should always be a single line of text (its contents are guaranteed to contain plain text without HTML markup), it should be at most 100px wide, and if the text is longer, it should be clipped.

Unfortunately, when the text gets long, the cell still stretches. Tested in IE and FF, both of which are among my target browsers.

Suggestion to add a <div> inside the cell and set the width to that is difficult. The table is generated from a gridview control and that just adds the specified column width to the <td> element and inserts the text as-is.

like image 316
Vilx- Avatar asked Sep 09 '11 08:09

Vilx-


People also ask

How do you fix the width of a table cell in HTML?

Using width attribute: The <td> tag has width attribute to control the width of a particular column. By assigning a numeric value to this attribute between 0 to 100 in terms of percentage(or you can use pixel format). We can restrict the column width up to that much percentage of the table's total width.

How do I restrict column width in HTML table?

Use the style attribute with the width or height properties to specify the size of a table, row or column.

What does white space Nowrap mean?

nowrap : Multiple whitespaces are collapsed into one, but the text doesn't wrap to the next line.

How do I restrict table width in CSS?

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

You can set max-width:100px. Live example: http://jsfiddle.net/tw16/RuAVq/

td{
    width: 100px;
    max-width: 100px; /* add this */
    white-space: nowrap;
    overflow: hidden;
}

The problem is, typically, IE doesn't support this.

Another solution, which is supported by IE, is to use float:left. Live example: http://jsfiddle.net/tw16/RuAVq/1/

td{
    width: 100px;
    float: left; /* add this */
    white-space: nowrap;
    overflow: hidden;
}
like image 93
tw16 Avatar answered Sep 21 '22 12:09

tw16