3

I have a fixed-width table (with variable-width columns). If a user enters long entries without spaces, the table expands horizontally and the layout breaks.

I can use word-break: break-all to fix this, but this breaks lines in the middle of words, even if there is a suitable space. Supposedly, this can be fixed with word-wrap: break-word, but, unfortunately, it doesn't work as expected in tables.

Here is an example with word-break: break-all and word-wrap: break-word:

<table style="width: 200px; border: 1px solid black;">
    <tr>
        <td style="word-wrap: break-word">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 
            incididunt ut labore et dolore magna aliqua.

            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        </td>
        <td>1234</td>
    </tr>
</table>

<table style="width: 200px; border: 1px solid black;">
    <tr>
        <td style="word-break: break-all">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 
            incididunt ut labore et dolore magna aliqua.

            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        </td>
        <td>1234</td>
    </tr>
</table>

and here is what I want it to look like:

+-----------------------------------+
| Lorem ipsum dolor sit amet,       |
| consectetur adipiscing elit,      |
| sed do eiusmod tempor             |
| incididunt ut labore et           |
| dolore magna aliqua.         1234 |
| aaaaaaaaaaaaaaaaaaaaaaaaaaaa      |
| aaaaaaaaaaaaaaaaaaaaaaaaaaaa      |
| aaaaaaaaaaaaaaaaaaaaaa            |
+-----------------------------------+

i.e. linebreaks within words if and only if there is no possibility to naturally break it.

I know that table-layout: fixed would make the table work with word-wrap: break-word, but then the columns would no longer be variable-width. I want to keep using a table instead of divs, since the data itself is tabular in nature.

Is there a way to do that in CSS?

Heinzi
  • 167,459
  • 57
  • 363
  • 519

1 Answers1

0

Not CSS, but you can use <wbr> to designate where to break a word (only if necessary).

<table style="width: 200px; border: 1px solid black;">
    <tr>
        <td>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 
            incididunt ut labore et dolore magna aliqua.

            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<wbr>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<wbr>aaaaaaaaaaaaaaaaaa
        </td>
        <td>1234</td>
    </tr>
</table>
jhpratt
  • 6,841
  • 16
  • 40
  • 50