How to Wrap the Content of a Table Cell

As we know, the contents of a table can change its structure or dimensions. So, there can be several difficulties with table cells. For example, long words in a table cell may cause the cell width to increase, or long words may cross the cell borders. But you can avoid these by using word wrapping on the cell content.

In this snippet, we suggest two methods: either using the CSS word-wrap or word-break property.

Solution with the CSS word-wrap property

Use the border-collapse property set to "collapse" and table-layout property set to "fixed" on the <table> element. Also, specify the width of the table. Then, set the word-wrap property to its "break-word" value for <td> elements and add border and width to them.

Example of wrapping the content of a table cell with the word-wrap property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      table {
        border-collapse: collapse;
        table-layout: fixed;
        width: 310px;
      }
      table td {
        border: solid 1px #666;
        width: 110px;
        word-wrap: break-word;
      }
    </style>
  </head>
  <body>
    <table>
      <tr>
        <td>1</td>
        <td>What is Lorem Ipsum?</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Why do we use it?</td>
        <td>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. </td>
      </tr>
    </table>
  </body>
</html>
If you want to wrap a word on a new line, use the word-wrap property, but if you need to break it at any appropriate character, use the word-break property.

Solution with the CSS word-break property

Here, we set the margin-left and margin-right properties to "auto" for the <table>, use the "fixed" value of the table-layout property and specify the border-spacing and width of the table. For <td> elements, add the border property and set the word-break to its "break-all" value.

Example of wrapping the content of a table cell with the word-break property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      table {
        border-spacing: 0px;
        table-layout: fixed;
        margin-left: auto;
        margin-right: auto;
        width: 310px;
      }
      td {
        border: 1px solid #666;
        word-break: break-all;
      }
    </style>
  </head>
  <body>
    <table>
      <tr>
        <td>1</td>
        <td>What is Lorem Ipsum?</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Why do we use it?</td>
        <td>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. </td>
      </tr>
    </table>
  </body>
</html>