Search code examples
htmlcsshtml-tablecss-tables

How to break after n characters with CSS?


I need to break my table cell every 20 characters.

I found out, that there is a ch unit in CSS that allows me to limit my max-width like this:

td {
    max-width: 20ch;
}

Doing this limits the width of my cell, but does not break/wrap my strings. I tried to apply word-wrap: break-word, but this also didn't help me.

td {
    max-width: 20ch;
    word-wrap: break-word; /* does not work */
}

By the way: Most of my cells contain strings without spaces. Maybe this is necessary information.

EDIT

Sorry for late edit, but after some investigation I found out that my <table> had the css attribute white-space: nowrap; by my table library. This caused my word-wrap: break-word; to loose effect.


Solution

  • You can use a monospace font which renders all characters at the same width and word-wrap:break-word, but the 20ch here in the snippet will result in 16 characters for some reason, so you'll need to find a setting that allows 20 characters, which here in my setup (Firefox on Mac) is 24ch:

    td {
      font-family: monospace;
      border: 1px solid #ddd;
      max-width: 24ch;
      word-wrap:break-word;
    }
    <table>
      <td>
        oiuhncoiuhOOSFwrevi987OINDVouhnweoriuhneaörlvjneriunONVWöoiunoiSAJunwrvwoiunVA
      </td>
    </table>