Search code examples
htmlhtml-table

Add multilevel headers to table


I am new to HTML. I have a table like this:

example

I would like to convert this image to a html table. I tried this but it doesn't work:

<table>
  <tr>
    <td>value</td>
    <td>value</td>
    <td>value</td>
    <td>value</td>
  </tr>
  <tr>
    <td>value</td>
    <td><table width="350" border="1">
    <tr>
    <td>
    <table>
    <tr><td>value</td></tr>
    <tr><td>value<br>value <br>value<br>value<br></td></tr>
    </table>
    </td>
    <td>value</td>
    <td>value</td>
    <td>value</td>
    <td>value</td>
    </tr>
    </table></td>
    <td>
    <table width="100" border="1">
    <tr>
    <td>value</td>
    <td>value</td>
    </tr>
    </table>
    </td>
    <td>
    <table width="100" border="1">
    <tr>
    <td>value</td>
    <td>value</td>
    </tr>
    </table></td>
  </tr>
  <tr>
    <td>value</td>
    <td>value</td>
    <td>value</td>
    <td>value</td>
  </tr>
  <tr>
    <td>value</td>
    <td>value</td>
    <td>value</td>
    <td>value</td>
  </tr>
  <tr>
    <td>value</td>
    <td>value</td>
    <td>value</td>
    <td>value</td>
  </tr>
</table>

Solution

  • Use the colspan attribute on your th elements:

    table, th, td {
      border: 1px solid black;
      border-collapse: collapse;
    }
    <table>
      <tr>
        <th>Title 1</th>
        <th colspan="2">Title 2</th>
        <th>Title 3</th>
      </tr>
      <tr>
        <td>Subtitle 1.1</td>
        <td>Subtitle 2.1</td>
        <td>Subtitle 2.2</td>
        <td>Subtitle 3.1</td>
      </tr>
      <tr>
        <td>1.1 value</td>
        <td>2.1 value</td>
        <td>2.2 value</td>
        <td>3.1 value</td>
      </tr>
    </table>

    You can read more about the table HTML element here.