Home > Net >  white-space: nowrap; adjust table column width
white-space: nowrap; adjust table column width

Time:01-03

I've set these columns width by percent (%)

Without white-space: nowrap; the column width is following settings (20%, 20%, 20%, 15%, 15%, 10%)

.cell-component {
  width: 90%;
  background-color: aqua;
  // white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
 }

enter image description here

I want to hidden text if it is overflow, so I need to add white-space: nowrap; I hope with will keep both the percent (20%, 20%, 20%, 15%, 15%, 10%) and hidden text if overflow, but the actual it automatic set width for these columns

.cell-component {
  width: 90%;
  background-color: aqua;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
 }

enter image description here

Any ideas to resolve this problem? Please give some feedback if I have any wrong thing on my code. Thank you.

CodePudding user response:

To set the width for the columns you can use colgroup and set table-layout to fixed. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup

  <colgroup>
    <col style="width:20%">
    <col style="width:20%">
    <col style="width:20%">
    <col style="width:15%">
    <col style="width:15%">
    <col style="width:10%">
  </colgroup>  

* {
  padding: 0;
  margin: 0;
}
table {
  width: 100%;
  table-layout: fixed; // set table layout
}

.cell-component {
  background-color: aqua;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  column-width: auto;
 }
 <table border="1">
  <colgroup>
    <col style="width:20%">
    <col style="width:20%">
    <col style="width:20%">
    <col style="width:15%">
    <col style="width:15%">
    <col style="width:10%">
  </colgroup>  
  <tr>
    <td>Col 1</td>
    <td >Col 2</td>
    <td >Col 3</td>
    <td >Col 4</td>
    <td >Col 5</td>
    <td >Col 6</td>
  </tr>
  <tr>
    <td >lorem ipsum lorem ipsum</td>
    <td >lorem ipsum lorem ipsum</td>
    <td >lorem ipsum lorem ipsum</td>
    <td >lorem ipsum lorem ipsum</td>
    <td >lorem ipsum lorem ipsum</td>
    <td >lorem ipsum lorem ipsum</td>
  </tr>
</table> 

  • Related