htmlcsshtml-tabletablelayoutword-wrap

Ensure that table cell widths are respected


I have a HTML <table> with multiple cols. How do I ensure that the given cell/col width is respected in any case? That is to say that if I give a cell a width of 100px and if the text content is long (exceeds 100 chars without any spaces), the text content should respect the 100px width and wrap to next line..

I have already tried using word-wrap:break-word, but that does not work.


Solution

  • Use table-layout: fixed to ensure your td widths are respected.

    Check out the MDN docs for additional information.

    Edit

    Something like this should work for you:

    table {
        table-layout: fixed;
    }
    td {
        color:white;
        width:50px;
        background-color:Blue;
        word-wrap: break-word;
        max-width:50px;
    }
    

    Here's a working fiddle to demonstrate.