Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html table column width

Tags:

html

css

How to fix bottom column ? Width 50% not really working. I want to do 2 row and 3 row bottom same width.

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
    border: 1px solid black;
}
</style>
</head>
<body>

<table>
  <tr>
    <td style="width:50%;">Cell A</td>
    <td style="width:50%;">Cell B</td>
  </tr>
    <tr>
    <td>Cell A</td>
    <td>Cell B</td>
    <td>Cell B</td>
  </tr>
</table>

</body>
</html>
like image 592
Infed Avatar asked Sep 16 '25 21:09

Infed


1 Answers

Table columns are inter-connected. So that if you place some content that forces a cell to grow wider, the entire column grows wider.

That means that all rows must have the same number of cells. However, you can merge 2 or more cells by using colspan attribute.

If you want to have 2 columns on one row and 3 columns on others, you probably want to set 6 cells and use colspan in both cases:

td {
  border: 1px solid #eee;
  text-align: center;
}
<table style="width: 100%;">
  <tr>
    <td colspan="3" style="width:50%;">Cell A</td>
    <td colspan="3" style="width:50%;">Cell B</td>
  </tr>
  <tr>
    <td colspan="2">Cell A</td>
    <td colspan="2">Cell B</td>
    <td colspan="2">Cell C</td>
  </tr>
</table>

I made them 6 columns as it's easier to visualize. But, in reality the 2 columns on each side can be merged, as they are always colspan-ed together:

td {
  border: 1px solid #eee;
  text-align: center;
}
<table style="width: 100%;">
  <col width="33.3333%">
  <col width="16.6667%">
  <col width="16.6667%">
  <col width="33.3333%">
  <tr>
    <td colspan="2">Cell A</td>
    <td colspan="2">Cell B</td>
  </tr>
  <tr>
    <td>Cell A</td>
    <td colspan="2">Cell B</td>
    <td>Cell C</td>
  </tr>
</table>
like image 84
tao Avatar answered Sep 18 '25 13:09

tao