18

I need to create a complex table that has multiple nested rows.

My current understanding is that you can not have nested rows in an HTML table. For example,

<table>
  <tr>
    <td>header one</td>
    <td>header two</td>
  </tr>

  <tr>
    <td>One</td>
    <td>
      <!-- nested row -->
      <tr>
        <td>nested one</td>
        <td>nested two</td>
      </tr>
    </td>
  </tr>
</table>

Would expect to create:

enter image description here

This is a very simple exaple. The table that I need to generate has several more nested rows.

I know that there is the table attribute rowspan to set rows. However, I'm wondering if there are any open-source JavaScript libraries or alternative methods for creating nested table rows, without having to use the rowspan attribute.

2 Answers 2

30

You need to wrap the nested tr in a new table element first. So it looks like:

table { width: 100%; border-collapse: collapse;}
td { border: 1px solid #000; }
td table { 
  margin: -2px;
  width: calc(100% + 4px);
}
<table>
      <tr>
        <td>header one</td>
        <td>header two</td>
      </tr>
    
      <tr>
        <td>One</td>
        <td>
    
          <!-- nested row -->
          <table>
           <tr>
             <td>nested one</td>
           </tr>
           <tr>
             <td>nested two</td>
           </tr>
          </table>
    
        </td>
      </tr>
    </table>

tr can only be a child of a table, thead, tfoot, etc.

rowspan is much easier to style, though:

table { width: 100%; border-collapse: collapse; }
td { border: 1px solid #000; }
    <table>
      <tr>
        <td>header one</td>
        <td>header two</td>
      </tr>
    
      <tr>
        <td rowspan="2">One</td>
        <td>nested one</td>
      </tr>
      <tr>
        <td>nested two</td>
      </tr>
    </table>

Sign up to request clarification or add additional context in comments.

2 Comments

<td rowspan="2">One</td>
rowspan and colspan. thx.
4

You'd have to create a nested table:

<td>
  <!-- nested row -->
  <table>
    <tr>
      <td>nested one</td>
      <td>nested two</td>
    </tr>
  </table>
</td>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.