How to Set the Table Column Width Regardless of the Text Amount in its Cells

When working with tables, you may come across the difficulty of setting the width of the table, which does not depend on the amount of text in the cells. Sometimes, when the text in one of the cells of the column is too long, the column’s width change.

In this snippet, we’ll demonstrate how to overcome this problem step by step and then you can try the full example.

Create HTML

  • Use a <table> element.
  • Add two <tr> elements with <th> elements within each of them.
<table>
  <tr>
    <th>header 1235466549845</th>
    <th>header 2, Lorem Ipsum</th>
  </tr>
  <tr>
    <td>Some text</td>
    <td>This is a loooooooooooooooong text for exampeeeeeeeele.</td>
  </tr>
</table>

Add CSS

  • Specify the border and width properties of the <table> element and set the table-layout to “fixed”.
  • Specify the border and width properties of the <th> and <td> elements.
table {
  border: 1px solid #666;
  table-layout: fixed;
  width: 180px;
}

th,
td {
  border: 1px solid #666;
  width: 90px;
  overflow: hidden;
}

Now, you can try the full example.

Example of setting the table column width:

<!DOCTYPE html>
<html>
  <head>
    <style>
      table {
        border: 1px solid #666;
        table-layout: fixed;
        width: 180px;
      }
      th,
      td {
        border: 1px solid #666;
        width: 90px;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <table>
      <tr>
        <th>header 1235466549845</th>
        <th>header 2, Lorem Ipsum</th>
      </tr>
      <tr>
        <td>Some text</td>
        <td>This is a loooooooooooooooong text for exampeeeeeeeele</td>
      </tr>
    </table>
  </body>
</html>

Result

header 1235466549845 header 2, Lorem Ipsum
Some text This is a loooooooooooooooong text for exampeeeeeeeele