Search code examples
htmlcsshtml-table

How to break a long word in a table TD element?


Here I have a table in which I want to break a long word into multiple lines by changing its cell width (e.g. as 20px), like below:

<table cellspacing="0" cellpadding="1" style="border-collapse: collapse;">
        <tbody>
            <tr >
                <td>
                123
                </td>
                <td>123</td>
                <td style="width: 20px;">
                    canyouhelpmebreakintolineswith20pxwidth?</td>
            </tr>
            <tr>
                <td>
                abc
                </td>
                <td>
                def
                </td>
                <td style="width: 20px;">
                placeholder
                </td>
            </tr>
        </tbody>
</table>

CSS:

table {border-collapse:collapse; table-layout:fixed;}
table td {
  border-width: 1px;
  border:solid 1px; 
  word-wrap:break-word;}

I even made the width of the whole columns as 20 px, and I used table-layout as fixed and word-wrap as break-word, but the cell width still refused to change. Can you please point me where I am wrong?

Below is the JS Fiddle link:

https://jsfiddle.net/flyingbee2012/nxzjof9d/21/


Solution

  • I think you're trying to implement the solution described here: force line break in html table cell If you want to automatically wrap a word then you have to add the width of the table itself. In your case set the width of the table to 100% to create equal sized columns that automatically wrap. I prepared a small example with 80% width and the 20px column here.

    <html>
    <body>
        <table cellspacing="0" cellpadding="1" style="border-collapse: collapse;">
            <tbody>
                <tr >
                    <td>
                    123
                    </td>
                    <td>123</td>
                    <td style="width: 20px">
                        canyouhelpmebreakintolineswith20pxwidth?</td>
                </tr>
                <tr>
                    <td>
                    abc
                    </td>
                    <td>
                    def
                    </td>
                    <td>
                    </td>
                </tr>
            </tbody>
        </table>
    </body>
    </html>
    

    And the css:

    table {border-collapse:collapse; table-layout:fixed; width: 80%}
    table td {
      border-width: 1px;
      border:solid 1px; 
      word-wrap:break-word;}