Skip to content Skip to sidebar Skip to footer

How Can I Set A 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. ('vis

Solution 1:

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.


Solution 2:

CSS Solution

"Truncate" may not be the word you are looking for. You may just want to hide the overflowing characters. If that is the case, look into the css-property "overflow," which will hide any content extending past the declared limits of its container.

td div.masker {
  height:25px;
  width:100px;
  overflow:hidden;
}

<td>
  <div class="masker">
    This is a string of sample text that
    should be hidden when it reaches out of the bounds of the parent controller.
  </div>
</td>

Javascript Solution

If you are indeed wanting to truncate the text within the container, you will have to remove one character from the right, test the width of the parent, and continue to remove characters and testing the parent width until the parent width matches the declared width.

while (parent.width > desiredWidth) {
  remove one char from right-side of child-text
}

Solution 3:

<td id="td1" style="overflow-x:hidden;">

Should be

<td id="td1" style="overflow:hidden;">

overflow-x is a Microsoft CSS attribute, which is now part of CSS3. I would stick with the older overflow attribute.

EDIT:

As Paolo mentions you also need to add table-layout:fixed; and specify the width of the table. A full example follows.

<html>
<head>
<style>
    table
    {

        table-layout:fixed;
        width:100px;
        }
td
{
    overflow:hidden;
    width:50px;
    border-bottom: solid thin;
    border-top:solid thin;
    border-right:solid thin;
    border-left:solid thin;

}
</style>
</head>
<body>
<table>
<tr><td>Some_long_content</td><td>Short</td></tr>
</table>
</body>
</html>

Solution 4:

As far as I know, a table cell will always stretch to accommodate its contents.

Have you thought about using Javascript to dynamically truncate the data in table cells that have more than a certain amount of content? Alternatively, you could do this more easily server side.


Solution 5:

You could use jQuery or plain javascript to surround the content of your cell(s) with div tags and set a fixed width and overflow:hidden on those instead. Not beautiful, but it'd work.

ETA:

<td><div style="width:30px;overflow:hidden">Text goes here</div></td>

Since the DIV is the bounding element, that's where the width should be set.


Post a Comment for "How Can I Set A Width To Visually Truncate Its Displayed Contents?"