Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure css tree with borders

Tags:

css

I am trying to create a tree with indentations in pure CSS. I have been trying using something like:

ul.tree ul {
  padding-left: 5px;
}

However I would like to have a separation between each item in the list. If I use the code above the separating bar gets indented as well so it's not too good.

Here is my current code (I do the indent directly in js, which I don't like): jsfiddle

Ultimately, I want to create something that basically looks like that:

tree example

Any idea how to do this in pure CSS? kudos for the simplest answers.

like image 538
edeboursetty Avatar asked Dec 26 '22 16:12

edeboursetty


2 Answers

Simple with Multi-level Depth Support

UPDATED: Tweaked to accommodate hover

No extra HTML needed, no having to limit depth because of css selector chaining, as it supports any number of levels deep without having to adjust your css at all for those levels (no keeping track of "padding" to set on the next level deep).

This works well with only a two minor limitations (which I don't believe will factor into affecting you).

See fiddle demo.

Add a position: relative to your ul.tree, but keep all the child elements the default static position. Then change/add the following css:

ul.tree a {
  display: block;
  height:30px;
  line-height: 30px;
  padding-left: 15px;
}

/* this is making our bottom border, but sizing off the .tree ul width */
ul.tree a:before { 
  content: '';
  height: 30px; /* match your <a> height */
  position: absolute;
  left: 0;
  right: 0;
  z-index: -1;
  border-bottom-width: 1px;
  border-bottom-color: lightgray;
  border-bottom-style: solid;
}


ul.tree a + ul {
    padding-left: 15px; /* this is your spacing for each level */
}

ul.tree a:hover:before {
  background-color: #DDDDDD;
}

The limitations are that no child elements can have a position set and we are using a pseudo-element (which means it cannot be used for some other feature, but that is probably not an issue either).

like image 194
ScottS Avatar answered Feb 06 '23 23:02

ScottS


For lists with unknown depths, I've used an absolutely positioned element for separating lines. It adds a little extra markup, but seems to work.

div.separator {
    position:absolute;
    left:0px;
    right:0px;
    border-top:1px solid lightgray;
}
<ul class="tree">
    <li><a>Item1</a><div class="separator"></div></li>
    <li><a>Item2</a><div class="separator"></div>
        <ul>
            <li><a>Item3</a><div class="separator"></div></li>
            <li><a>Item4</a><div class="separator"></div></li>
            <li><a>Item5</a><div class="separator"></div>
                <ul>
                    <li><a>Item6</a><div class="separator"></div></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

http://jsfiddle.net/7u87c/20/

like image 31
showdev Avatar answered Feb 07 '23 00:02

showdev