Jonathan Carter
Jonathan Carter

Reputation: 1039

Styling a table with fixed width columns and overflow text

I've got a <table> that contains a few columns whose textual value can be too long, therefore I wan't to "trim" them using "text-overflow: ellipsis" and "overflow: hidden" on the <td>'s in CSS. I noticed that in order for me to do that I have to set "table-layout: fixed" on the <table> which then forces me to specifically set every single column's width.

I didn't want to apply a bunch of class names or IDs to the columns, so I used the following CSS solution:

#error-list th:nth-child(1),
#error-list th:nth-child(6) {
    width: 53px;
}

#error-list th:nth-child(2) {
    width: 131px;
}

#error-list th:nth-child(3) {
    width: 226px;
}

#error-list td:nth-child(3),
#error-list td:nth-child(4) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

The column list is fixed, so it isn't a big deal that I'm using the column's ordinal to style it, and I'm happy that the markup is leaner. This solution works great, but I wanted to ask whether there is a better solution.

In order for the above to work, I had to set the column width's such that it took account for padding and border as well. That way it would work in IE, Chrome and FF. It feels pretty nasty doing it this way, but when I tried using "-webkit-box-sizing: content-box" (so I could set the column widths without having to also worry about padding/border), Chrome didn't respect it.

Am I doing something wrong? Is there a better way? I don't mind having to hard-code every column width, but I hate having to use the border-box box-sizing.

Upvotes: 4

Views: 5368

Answers (1)

user641656
user641656

Reputation:

I'm not sure if this is what you're looking for, but this is what I came up with: http://jsfiddle.net/e7ZKq/1/

If you set a max-width to your td rule along with your other properties, the cells will fit to the content until you hit that max width and then it will cutoff the remainder with the ellipsis.

Upvotes: 2

Related Questions