Infed
Infed

Reputation: 87

html table column width

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>

Upvotes: 4

Views: 25305

Answers (3)

tao
tao

Reputation: 90013

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>

Upvotes: 6

MichaelvE
MichaelvE

Reputation: 2578

You can use colspan to tell the browser how many columns to want a cell to occupy:

<!DOCTYPE html>
<html>

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

<body>

  <table width="100%">
    <tr>
      <td>Cell A</td>
      <td colspan="2">Cell B</td>
    </tr>
    <tr>
      <td>Cell A</td>
      <td>Cell B</td>
      <td>Cell B</td>
    </tr>
  </table>

</body>

</html>

Upvotes: 0

zer00ne
zer00ne

Reputation: 43861

Use colspan='2' on first row second column.

<!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 colspan='2' style="width:50%;">Cell B</td>
  </tr>
    <tr>
    <td>Cell A</td>
    <td>Cell B</td>
    <td>Cell B</td>
  </tr>
</table>

</body>
</html>

Upvotes: 1

Related Questions