The last we left our pure-CSS tree component, it could render both horizontally oriented as well as vertically oriented as well as the inverse direction for either. With each orientation now capable of being rendered in either direction, might we be able to build a tree component that could put the root node in the center of the graph and have half of the descendant graph render to left and have to the right (for the horizontal orientation) or half to the top and half to the bottom (for the vertical orientation)?
I will be honest, I was actually pleasantly surprised at how simple this was. Our foundation is solid, so there is little we need to add. Let’s start with the vertical tree first this time. We want to add a .-centered
modifier that will work in conjunction with the .-vertical
modifier to create a bi-directional vertical tree.
In the HTML structure, our centered tree will need to only have on child <li>
of our outermost <ul>
, which will be the center of the tree. If we start simply with the (S)CSS we have right now and update our HTML structure, we get this:
See the Pen css-tree-vertical-centered__1 by Stephen Margheim (@smargh) on CodePen.
Our first two children (1.1
and 1.2
) look connected properly, but the next two children (1.3
and 1.4
) are hanging out at the bottom of the tree disconnected. What we want is to move the first two children to the top (invert their direction) and allow the second two children to connect at the bottom.
We start crafting our .-centered
modifier by targeting our central node (> li:only-child
) and then its last two children (> ul:first-of-type:nth-last-child(2)
). We can then essentially bring in the inversion code:
See the Pen css-tree-vertical-centered__2 by Stephen Margheim (@smargh) on CodePen.
1.1
and 1.2
are now inverted, but are sitting at the bottom of the tree with our primary node (1
) still at the top. We can focus next on reordering our sub-trees to get them flowing vertically in the correct order:
See the Pen css-tree-vertical-centered__3 by Stephen Margheim (@smargh) on CodePen.
This gets us very close, as we now only need to reorder our primary node label to put it in the middle
See the Pen css-tree-vertical-centered by Stephen Margheim (@smargh) on CodePen.
Wonderful! Our .-vertical.-centered
combined implementation looks lovely.
I won’t walk thru the steps, as they are functionally the same, for the horizontal direction. Instead, let’s just marvel at the final result:
See the Pen css-tree-horizontal-centered by Stephen Margheim (@smargh) on CodePen.
As always, inspect the SCSS tab in the CodePens to see the source code for this implementation.
In the next part of this journey, I want to look over all of our SCSS and refactor things to consolidate and simplify our code.