John MacIntyre John MacIntyre - 1 year ago 49
CSS Question

How can I set a <td> width to visually truncate its displayed contents?

I'm trying to set a column width of a table, which works fine until it gets to the point where child elements would be visually truncated ... then it won't size any smaller. ("visually truncated"-what doesn't fit appears to be hidden behind the next column)

Here is some sample code to demonstrate my problem:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<script language="javascript" type="text/javascript">
var intervalID = null;

function btn_onClick()
// keep it simple, only click once
var btn = document.getElementById("btn");
btn.disabled = true;
// start shrinking
intervalID = window.setInterval( "shrinkLeftCell();", 100);

function shrinkLeftCell()
// get elements
var td1 = document.getElementById("td1");
var td2 = document.getElementById("td2");

// initialize for first pass
if( "undefined" == typeof( td1.originalWidth))
td1.originalWidth = td1.offsetWidth;
td1.currentShrinkCount = td1.offsetWidth;

// shrink and set width size
td1.width = td1.currentShrinkCount; // does nothing if truncating!

// set reporting values in right cell
td2.innerHTML = "Desired Width : ["
+ td1.currentShrinkCount
+ "], Actual : ["
+ td1.offsetWidth + "]";

// Stop shrinking
if( 1 >= td1.currentShrinkCount)
<table width="100%" border="1">
<td id="td1">
<td id="td2">
Desired Width : [----], Actual : [----]

<button id="btn" onclick="btn_onClick();">Start</button>

I've tried setting the width in different ways including

td1.offsetWidth = td1.currentShrinkCount;


td1.width = td1.currentShrinkCount + "px";

and = td1.currentShrinkCount + "px";

and = td1.currentShrinkCount;


td1.scrollWidth = td1.currentShrinkCount;

and = "hidden";
td1.width = td1.currentShrinkCount;

and = "scroll";
td1.width = td1.currentShrinkCount;

and = "auto";
td1.width = td1.currentShrinkCount;

I realize, I could probably use DIV's, but I'd prefer not to since the table is being generated from a bound control, and I don't really want to get into rewriting controls.

Having said that, I thought as a last ditch effort, I could at least wrap each 'td1's contents with a DIV, and the overflow would take care of things, but even replacing

<td id="td1">


<td id="td1" style="overflow:hidden;">
<div style="margin=0;padding:0;overflow:hidden;">

didn't work.

Does anybody know how I can set a width to visually truncate its contents?

BTW-My target browser is IE7. Other browsers are not important right now, since this is an internal app.

Answer Source

I just tried adding table-layout: fixed; to the <table> and it worked for me on IE7.

In a fixed table layout, the horizontal layout only depends on the table's width, the width of the columns, and not the content of the cells

Check out the documentation.