Search code examples
htmlhtml-tablehtml-tbody

How to create a nested four column table layout?


I am attempting to create a nested 4 column table layout, see image below. However, I am not certain, how to add the last row of data, so it is nested under the Date row. I have provided a snippet from a codepen, which displays the issue. Can anyone provide any assistance?

Image image

Code Snippet:

<table>
  <thead>
    <tr colspan="5">
      <th>Regian</th>
      <th>Q1 2010</th>
      <th>Q2 2010</th>
      <th>Q3 2010</th>
      <th>Q4 2010</th>
    </tr>
  </thead>
  <tbody className="labels">
    <tr>
      <td colSpan="5">
        <label htmlFor="accounting">Accounting</label>
        <input
          type="checkbox"
          name="accounting"
          id="accounting"
          data-toggle="toggle"
        ></input>
      </td>
    </tr>
  </tbody>
  <tbody className="hide" id="accounting-data">
    <tr>
      <td>Date</td>
      <td>Australia</td>
      <td>$3,544.00</td>
      <td>$5,834.00</td>
      <td>$10,583.00</td>
      <tr>
        <td>Central America</td>
        <td>$7,685.00</td>
        <td>$3,544.00</td>
        <td>$5,834.00</td>
        <td>$10,583.00</td>
      </tr>
    </tr>
  </tbody>
</table>


Solution

  • You've got several syntax errors in there, beyond that just missing a rowspan on a cell and you had more columns in your html than your example shows. See updated example below. Also not sure if all the separate tbody tags serve some sort of purpose but left them in there for ya since technically it's still valid markup. Cheers.

    table {
      border-collapse: collapse;
    }
    
    td, th {
      border: #0f0 1px solid;
      padding: .2rem;
    }
    <table>
      <thead>
        <tr colspan="5">
          <th>Regian</th>
          <th>Q1 2010</th>
          <th>Q2 2010</th>
          <th>Q3 2010</th>
          <th>Q4 2010</th>
        </tr>
      </thead>
      <tbody className="labels">
        <tr>
          <td colSpan="5">
            <label htmlFor="accounting">Accounting</label>
            <input
              type="checkbox"
              name="accounting"
              id="accounting"
              data-toggle="toggle"
            />
          </td>
        </tr>
      </tbody>
      <tbody className="hide" id="accounting-data">
        <tr>
          <td rowspan="2" style="vertical-align: top">Date</td>
          <td>Australia</td>
          <td>$3,544.00</td>
          <td>$5,834.00</td>
          <td>$10,583.00</td>
        </tr>
        <tr>
          <td>Central America</td>
          <td>$7,685.00</td>
          <td>$3,544.00</td>
          <td>$5,834.00</td>
        </tr>
      </tbody>
    </table>