Tree structure plays an important role in displaying hierarchical structure. It may be displaying an structure for employee, family or any. We will be learning to create a Tree structure using css and html only.
Tree Structure demo at the bottom
As mentioned earlier, we will be using plain html & css for our tree strucutre. Dont take it easliy as it can be done by the use of using image also. But it has some drawbacks.
Images take time to download, as it require many images at many places, so using many images can make your webpage slow. As every image take seperate HTTP request to server. For that case we will use image where ever necessary.
Key Concept for our Tree Structure :
We have use CSS as our power in this tutorial. Below we can see the arrow in the image.
Don’t get confused this is not an image, rather we have used css for drawing lines. simply “Border” property. We all are familiar about this property but one more difficulty we faced in drawing this Tree Structure was to keep it aligned center. For resolving this what we did to use one more property in css called “-webkit-box-sizing: border-box” ( It need prefix as -webkit- , -moz- etc).
Here are the few css tricks for this Tree Structure. lets first check the levels
For the first level in tree : Below is an arrow which is centrally aligned. So the challenge is how to create it.
What we did we have used 2 Divs with 50% width, and assigned it “border-left” property and “box-sizing: border-box“. Below is rough idea.
In the very next level we have few more challenges for second level. What we have to create is as below.
for this section of tree structure we have divided whole div in 4 equal parts of width 25% each.
For the First 25%
Than in each part we have put a div, width of 100%, and divided in 2 equal parts of width 50% each.
And we have keep the first part with no border and second half div with a left border and top border.
By applying this we will get the shape as in the box 1 in the below image.
similarly for box we have to apply “border-top” and “border-right” left div with width 50%, and for another div with width 50% we need to apply “border-top”.
In the same way we need to apply for the rest other boxes, No matter how many boxes or how many people in level, by applying certain css tricks , we can draw as many as level in tree structure.
final result for tree structure as image :