Table Cells: white-space nowrap until a max-width has been met, then wrap

1.8k Views Asked by At

In the example below, I want the cells to not wrap until they've reached the max-width. This would still cause the table to overflow, which is the behavior I want.

main {
  max-width: 600px;
  overflow: hidden;
}

th {
  background: #ccc;
  padding: 2px 5px;
  white-space: nowrap;
  max-width: 120px;
}
<main>
  <table>
  <tr>
    <th>One</th>
    <th>One Two</th>
    <th>One Two Three</th>
    <th>Four</th>
    <th>Five</th>
    <th>Six</th>
    <th>Seven</th>
    <th>Seven Eight</th>
    <th>Seven Eight Nine</th>
    <th>Seven Eight Nine Ten</th>
  </tr>
  </table>
</main>

3

There are 3 best solutions below

3
Stanley On

This is simply not possible in css without javascript. I have made a short script that checks if the width is greater than 119 and if so sets that elements style to normal wrapping as you wanted.

 var a = document.querySelectorAll("th");

 a.forEach((a) => {
   if(a.offsetWidth > 119) {
     a.style.whiteSpace = "normal";
   }else {
     console.log(a.offsetWidth);
   }

 });

enter image description here


Full code


html

<main>
  <table>
  <tr>
    <th class="t">One</th>
    <th>One Two</th>
    <th>One Two Three</th>
    <th>Four</th>
    <th>Five</th>
    <th>Six</th>
    <th>Seven</th>
    <th>Seven Eight</th>
    <th>Seven Eight Nine</th>
    <th>Seven Eight Nine Ten</th>
  </tr>
  </table>
</main>

<script type="text/javascript">

     var a = document.querySelectorAll("th");

     a.forEach((a) => {
       if(a.offsetWidth > 119) {
         a.style.whiteSpace = "normal";
       }else {
         console.log(a.offsetWidth);
       }

     });

</script>

css

main {
  max-width: 600px;
  overflow: hidden;
}

th {
  background: #ccc;
  padding: 2px 5px;
  white-space: nowrap;
  max-width: 120px;
}
0
Hassan Hosseini On

You can use this:

add word-wrap: break-word; and remove white-space: nowrap;

Css:

main {
  max-width: 600px;
  overflow: hidden;
}

th {
  background: #ccc;
  padding: 2px 5px;
  max-width: 120px;
  word-wrap: break-word;
}

Html code:

<main>
  <table>
  <tr>
    <th>One</th>
    <th>One Two</th>
    <th>One Two Three</th>
    <th>Four</th>
    <th>Five</th>
    <th>Six</th>
    <th>Seven</th>
    <th>Seven Eight</th>
    <th>Seven Eight Nine</th>
    <th>Seven Eight Nine Ten</th>
  </tr>
  </table>
</main>

The result is:

enter image description here

0
Noor Nabiul Alam Siddiqui On

Just remove

white-space: nowrap;

See example

The Result