0

As titled.

Possible similar to Using "word-wrap: break-word" within a table but the answers did not resolve my problem.

Example:

| --<td style="width:100px">(example)-- |
|                                       |
| Example 1:                            |
| something long something something something | <- this line should break into below:
|                                       |
| something long something something    |
| something                             | <- when break at word is possible
|                                       |
|                                       |
| Example 2:                            |
| somethinglongsomethingsomethingsomethingsomething | <- this line should break into below:
|                                       |
| somethinglongsomethingsomethingsometh |
| ingsomething                          | <- when break at word is not possible

It seems like I can either use break-word or break-all.

For break-word, example 1 works but example 2 stretches the table, regardless if I set table-layout: fixed in the table or not.

For break-all, example 2 works but example 1 also breaks the word.

Is there any clever way to let the table break the word only when it have to?

Community
  • 1
  • 1
Tide Gu
  • 815
  • 1
  • 7
  • 21

1 Answers1

1

There's no direct HTML-only or CSS-only way to do this.

You could go overkill and use a javascript solution, however. One strategy: estimate the maximum number of characters which would fit in one line of the table cel, search the string within the table cel for single words which are longer than that number, and insert a <wbr> tag in the word (or hyphenate it, or add a space, or etc) at that point.

$('td').each(function() {
  var contents = $(this).html();
  contents = contents.replace(/(\w{25})/g,"$1<wbr>");
  $(this).html(contents);
  });
td {border:1px solid; max-width: 15em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>This has short words</td>
  </tr>
  <tr>
    <td>This has a long word: bababadalgharaghtakamminarronnkonnbronntonnerronntuonnthunntrovarrhounawnskawntoohoohoordenenthurnuk!</td>
  </tr>
  </table>
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
  • Fantastic! Now I need to figure out how to do it when there are many `td`s with different width, and also the backward compatibility with non-HTML5 browsers! Thanks! BTW, never saw `` before, learnt something absolutely new! – Tide Gu Jun 08 '16 at 23:40
  • I suppose in theory you could spam a tag in between every letter of long words, rather than try to estimate the "correct" number for each column, but I'm not sure if that would cause rendering issues with large amounts of content... – Daniel Beck Jun 08 '16 at 23:46