Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I construct a table header than spans multiple rows in HTML?

I would like to construct a table as follows:

|   Major Heading 1    |  Major Heading 2    | |   Minor1  |  Minor2  | Minor3  |  Minor4   | ---------------------------------------------- |   col1    |   col2   |   col3  |    col4   | rest of table ... 

Seeing as how there is only 1 line for TH elements, how can I construct the header row such as the columns line up? Hierarchical tables doesn't seem like a good option because the column widths won't line up, and I also can't use two rows with TH tags with colspan.

like image 932
statguy Avatar asked Sep 08 '13 03:09

statguy


People also ask

How do I span multiple rows in HTML cell?

The rowspan attribute in HTML specifies the number of rows a cell should span. That is if a row spans two rows, it means it will take up the space of two rows in that table. It allows the single table cell to span the height of more than one cell or row.

What do you call the table cells that span multiple rows or columns in HTML?

Table rows: The TR element. Table cells: The TH and TD elements. Cells that span several rows or columns.

How do you create cells that span more than one column or row?

To make a cell span more than one column, use the colspan attribute.


2 Answers

This is how I would do it (working fiddle at http://jsfiddle.net/7pDqb/) Tested in Chrome.

th, td { border: 1px solid black }
<table>    <thead>      <tr>        <th colspan="2">Major 1</th>        <th colspan="2">Major 2</th>      </tr>      <tr>        <th>col1</th>        <th>col2</th>        <th>col3</th>        <th>col4</th>      </tr>    </thead>    <tbody>      <tr>        <td>data1</td>        <td>data2</td>        <td>data3</td>        <td>data4</td>      </tr>    </tbody>  </table>
like image 96
tvanfosson Avatar answered Oct 07 '22 03:10

tvanfosson


Were you accidentally using rowspan instead of colspan? Or did you accidentally forget a closing </tr> tag?

Extending off of tvanfosson's answer, I'd use the scope attribute on the th elements for semantic and accessibility purposes:

th, td { border: 1px solid black }
<table>    <thead>      <tr>        <th colspan="2" scope='colgroup'>Major Heading 1</th>        <th colspan="2" scope='colgroup'>Major Heading 2</th>      </tr>      <tr>        <th scope='col'>Minor1</th>        <th scope='col'>Minor2</th>        <th scope='col'>Minor3</th>        <th scope='col'>Minor4</th>      </tr>    </thead>    <tbody>      <tr>        <td>col1</td>        <td>col2</td>        <td>col3</td>        <td>col4</td>      </tr>    </tbody>  </table>
like image 40
rink.attendant.6 Avatar answered Oct 07 '22 03:10

rink.attendant.6