dmx
dmx

Reputation: 1990

HTML: how to use colspan and rowspan?

I am trying to build a very simple array, but somehow It is not working How I think it should. Here is an example:

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

<table width=100%>
  <tr>
    <th colspan="8">sigle row of 8 cols</th>
  </tr>
  <tr >
    <td colspan="2">2 cols </td>
    <td rowspan="3" colspan="6" > 6 cols</td>
  </tr>
  <tr>
    <td colspan="2">2 cols</td>
  </tr>
    <tr>
    <td colspan="2">2 cols</td>
  </tr>
</table>

</body>
</html>

Please help me to debug. I want the months to occupy only 2 column and the saving to occupy 6 columns (the rest), but, this is not working as expected. I know the answer is trivial, but I cannot find it. Can you please tell me what is wrong?

Upvotes: 1

Views: 527

Answers (2)

Jon P
Jon P

Reputation: 19772

The table will have 8 columns, but you have effectively reduced it to 2. The table rendering algorithm will make things as efficient as it can.

By adding an additional row you can see what is happening

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

<table width=100%>
  <tr>
    <th colspan="8">Monthly Savings</th>
  </tr>
  <tr >
    <td colspan="2">January</td>
    <td rowspan="3" colspan="6" >$30000</td>
  </tr>
  <tr>
    <td colspan="2">February</td>
  </tr>
    <tr>
    <td colspan="2">March</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
  </tr>
</table>

</body>
</html>

What you are better off doing is assigning width to the columns

table, th, td {
    border: 1px solid black;
}
<table width=100%>
  <tr>
    <th colspan="2">Monthly Savings</th>
  </tr>
  <tr >
    <td style="width:33%">January</td>
    <td rowspan="3" style="width:66%" >$30000</td>
  </tr>
  <tr>
    <td>February</td>
  </tr>
    <tr>
    <td>March</td>
  </tr>
</table>

Upvotes: 3

Bhargav Chudasama
Bhargav Chudasama

Reputation: 7161

because the you add heading in single <th> so make id different

<th colspan="2">Monthly</th>
<th colspan="6">Savings</th>

so it will display 2 for month and 6 for saving

<!DOCTYPE html>
<html>

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

<body>

  <table width=100%>
    <tr>
      <th colspan="2">Monthly</th>
      <th colspan="6">Savings</th>
    </tr>
    <tr>
      <td colspan="2">January</td>
      <td rowspan="3" colspan="6">$30000</td>
    </tr>
    <tr>
      <td colspan="2">February</td>
    </tr>
    <tr>
      <td colspan="2">March</td>
    </tr>
  </table>

</body>

</html>

Upvotes: 1

Related Questions