Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create nested table rows

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.

like image 832
Kyle Avatar asked Feb 08 '17 16:02

Kyle


2 Answers

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>
like image 181
Adam Avatar answered Nov 14 '22 09:11

Adam


You'd have to create a nested table:

<td>
  <!-- nested row -->
  <table>
    <tr>
      <td>nested one</td>
      <td>nested two</td>
    </tr>
  </table>
</td>
like image 21
ADyson Avatar answered Nov 14 '22 08:11

ADyson