I have a table of hierarchical data (tree data structure) of varying depth and I want to render it using an HTML table in which just the content of the first column of the table will be indented according to the depth of each row that is known beforehand:
"comment one" (row=1, depth=0)
"comment two" (row=2, depth=0)
"comment three" (row=3, depth=1)
"comment four" (row=4, depth=2)
"comment five" (row=5, depth=0)
Now how can I achieve this?
And I know I can easily do it by defining CSS classes for each depth, but I am looking for a general solution.
CodePudding user response:
Alternative solution
Mr. Polywhirl answer may be what you are looking for. I still want to present an alternative solution. It doesn't fit what you need, but may be suited for other people browsing this question with different case.
For an automatic indentation, you can use CSS transform.
The trick is to rotate the table, in order to simulate indentation.
And then rotate the individual items in the opposite way to have them straight.
I like this solution for being polyvalent, it adapts to any number of item.
i = 3
function addElement(){
table = document.getElementById("indented-table");
table.innerHTML = `<tr><td>${ i}</td></tr>`;
}
#indented-table{
transform-origin: top left;
transform: skewX(20deg);
}
#indented-table tr{
background-color: #aaf;
transform: skewX(-20deg);
}
<table id="indented-table">
<tbody>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</tbody>
</table>
<button onclick="addElement()">Add</button>
CodePudding user response:
You can define a style to add padding to the table cells, based on the data attribute.
[data-row-depth="0"] { padding-left: 0; }
[data-row-depth="1"] { padding-left: 0.5rem; }
[data-row-depth="2"] { padding-left: 1.0rem; }
[data-row-depth="3"] { padding-left: 1.5rem; }
[data-row-depth="4"] { padding-left: 2.0rem; }
/* and so on... */
<table>
<thead>
<tr>
<th>Key</th>
</tr>
</thead>
<tbody>
<tr><td data-row-depth="0">A</td></tr>
<tr><td data-row-depth="1">A-1</td></tr>
<tr><td data-row-depth="2">A-1-1</td></tr>
<tr><td data-row-depth="3">A-1-1-1</td></tr>
<tr><td data-row-depth="1">A-2</td></tr>
<tr><td data-row-depth="0">B</td></tr>
<tr><td data-row-depth="0">C</td></tr>
<tr><td data-row-depth="1">C-1</td></tr>
</tbody>
</table>