I create a table and set the width of each column as a percentage. For example, the second column should be 30% wide, the fourth 10%. This works in many cases, but if the column name is long, the width of the whole column expands to the width of the column name. How can you avoid this behavior, create a table with a rigidly set (in percent) column width?

table { width: 100% } table>tbody>tr>td { width: 20% } table>thead>tr>th { padding: 10px; overflow: hidden; } table>tbody>tr>td:nth-of-type(2) { width: 30% } table>tbody>tr>td:nth-of-type(4) { width: 10% } 
 <table border=1> <thead> <tr> <th colspan=3>Group 1</th> <th colspan=2>Group 2</th> </tr> <tr> <th colspan=1>Group 3</th> <th colspan=4>Group 4</th> </tr> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> <th>TooLongColumn4Title</th> <th>Column 5</th> </tr> </thead> <tbody> <tr> <td>Value 1</td> <td>Value 2</td> <td>Value 3</td> <td>Value 4</td> <td>Value 5</td> </tr> <tr> <td>Value 1</td> <td>Value 2</td> <td>Value 3</td> <td>Value 4</td> <td>Value 5</td> </tr> <tr> <td>Value 1</td> <td>Value 2</td> <td>Value 3</td> <td>Value 4</td> <td>Value 5</td> </tr> </tbody> </table> 

  • The colgroup could solve the problem, but it overlaps thead styles, “erases” the necessary borders in a complex multi-level table header - Alaksander

1 answer 1

Set the word-break table : break-all

 table { width: 100%; word-break: break-all; } table>tbody>tr>td { width: 20% } table>thead>tr>th { padding: 10px; overflow: hidden; } table>tbody>tr>td:nth-of-type(2) { width: 30% } table>tbody>tr>td:nth-of-type(4) { width: 10% } 
 <table border=1> <thead> <tr> <th colspan=3>Group 1</th> <th colspan=2>Group 2</th> </tr> <tr> <th colspan=1>Group 3</th> <th colspan=4>Group 4</th> </tr> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> <th>TooLongColumn4Titlesfsgfsfgsdfg</th> <th>Column 5</th> </tr> </thead> <tbody> <tr> <td>Value 1</td> <td>Value 2</td> <td>Value 3</td> <td>Value 4</td> <td>Value 5</td> </tr> <tr> <td>Value 1</td> <td>Value 2</td> <td>Value 3</td> <td>Value 4</td> <td>Value 5</td> </tr> <tr> <td>Value 1</td> <td>Value 2</td> <td>Value 3</td> <td>Value 4</td> <td>Value 5</td> </tr> </tbody> </table> 

  • Well, where is the width of 2 columns in 30% and 4 in 10%? - Alaksander
  • And where is it? The problem, as follows from the question, is that long text stretches the cell. This problem has been resolved. Width set what you want. - humster_spb
  • Well, I wrote in the question “For example, the second column should be 30% wide, the fourth - 10%” should have - the keyword - Alaksander
  • @Alaksander, I corrected the answer - now this is what you need? - humster_spb