Search code examples
htmlcsshtml-tablewidth

Set max-width of text within a table td


I have a two column table. The second column contains cells that have some text in it, and then two inline icons that can be clicked to do something. However, if the text is too long, the inline icons start looking odd as they drop/wrap to the next line. The code is basically:

<td class="column-2">
    <span>...My very long text goes here...</span>
    <span class="inline-icon-one"></span>
    <span class="inline-icon-two"></span>
</td>

This is what the normal cell should look like

This is what it looks like with the long text

I was hoping to be able to set the max-width of the text within the cell. So if the cell is 300px, how can I set the text width to be a maximum of, lets say, 200px so that I have 100px left for my icons. This would prevent the inline icons from ever being positioned incorrectly. I also don't want the text to wrap, so I am fine with it just ending (or maybe even having an ellipses).

I have tried directly setting a 'max-width' and 'width: 75%' property to the text span, but that didn't work (it did not seem to have any effect).

This is the CSS I am using for the column:

td.column-2 {
    padding-left: 20px;
    height: 55px;
    width: 360px;
    vertical-align: middle;
    word-wrap: break-word;
    border-right: 1px solid transparent;
}

So the column/td width is set to 360px, so I would need to be able to set a smaller max-width on the span that represents the text, or if it is possible to set when the text starts wrapping.


Solution

  • I think I found the best possible solution for my case:

    I just added a 3rd column that would hold the inline icons. I reduced the width of the second row to 300px, and set the 3rd column width to be 60px. So it ends up as such:

    <td class="column-2">
        <span>...My very long text goes here...</span>
    </td>
    <td class="column-3">
        <span class="inline-icon-one"></span>
        <span class="inline-icon-two"></span>
    </td>
    

    With the CSS:

    td.column-2 {
        padding-left: 20px;
        height: 55px;
        width: 300px;
        vertical-align: middle;
        word-wrap: break-word;
        border-right: 1px solid transparent;
    }
    td.column-3 {
        height: 55px;
        width: 60px;
        vertical-align: middle;
        word-wrap: break-word;
        border-right: 1px solid transparent;
    }
    

    There was an answer that mentioned using javascript, but I was hoping to avoid that in my case and be able to purely do it via HTML and CSS.

    Thanks guys!