Building Pure CSS Trees (part 5)

After the first 4 parts of our series, we have some flexible (S)CSS that will render nested lists as trees. It can render horizontal trees, vertical trees, trees going from top-to-bottom or bottom-to-top, left-to-right or right-to-left , and even bracket-style centered trees.

All of this flexibility (and the SCSS code) can be seen in this comprehensive demo:

See the Pen css-trees by Stephen Margheim (@smargh) on CodePen.


This covers the basic needs of rendering trees, but I thought it might be fun to experiment a little with some edge cases.

The first experiment that came to mind was rendering a nested list as a “folder-style” list:

See the Pen css-trees__stacked by Stephen Margheim (@smargh) on CodePen.

This is an alteration, primarily, of the .-vertical modifier. Fundamentally, we use that foundation, set align-items: start on the li selector and style the child-to-parent connector, the sibling-to-sibling selector, and the sibling-to-sibling:last-child selector.

As with all of these demos, I haven’t extracted out the “magic numbers” into variables; though I have made sure to keep things consistent such that this shouldn’t be too difficult as an exercise for the reader.


Another fun experiment was to see if I could mix horizontal and vertical orientations for sub-trees. This is likely easier to understand by looking at the demo:

See the Pen css-trees__mixed__1 by Stephen Margheim (@smargh) on CodePen.

In this first demo, the tree is primarily in the horizontal orientation, so both 1.1 and 1.2 are laid out as we would expect for the .-horizontal modifier. The wrinkle comes when we throw the .-vertical modifier on 1.3 and 1.3 only. Here, we want the 1.3 sub-tree to render itself in a vertical orientation.

Interestingly, getting the modifiers to work on sub-trees immediately works for bi-directional trees as well:

See the Pen css-trees__mixed__2 by Stephen Margheim (@smargh) on CodePen.

As always, check out the (S)CSS in the CodePen to dig more into the details. And, if you have any questions, feel free to reach out to me on Twitter @fractaledmind. As you might have gathered, I think building tree structures with CSS is super-dope, so I’m always down to talk more about it.


Well, that’s it for this series on CSS trees. I genuinely hope you enjoyed it and found something interesting. As always, more to come.


All posts in this series