Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method for displaying a tree list using CSS only (no images or JS, example inside)

Tags:

html

css

I want to display something like this on a HTML page: enter image description here

With the restriction of using only CSS. The main problem lies in making these: |└ ├ "branches".

The example above was a solution I done myself. Each branch has the same width and consists of:

<ul>
    <li></li>
    <li></li>
</ul>

The trick is to turn the borders of <li> black accordingly. An image to show this (just a quick mock up) enter image description here

A problem I've encountered is turning the border white to match the background instead of transparent (apparently CSS has some problem with transparent borders on lists).

My question is: what's the most simplest solution? Is there a better way to do this?

EDIT: Some requirements:

  • The branch must have fixed width but the height must grow accordingly with the height of the table cell.
  • The two li elements must take up half of the row's height each such that the - in will always be in the middle.

EDIT2: http://en.wikipedia.org/wiki/Template:Tree_list did a little research. Alas, they use images for branches.

PS: As requested http://jsfiddle.net/q3zdB/2/

like image 408
meiryo Avatar asked Jan 20 '13 10:01

meiryo


1 Answers

The best I can come up with for this is some (unfortunately regrettable) nesting and use of generated content (so it does require a pretty up-to-date browser, so IE < 8 isn't going to look terribly pretty), however, that said, given the HTML:

ul {
  padding: 0;
  margin: 0;
  list-style-type: none;
  position: relative;
}
li {
  list-style-type: none;
  border-left: 2px solid #000;
  margin-left: 1em;
}
li div {
  padding-left: 1em;
  position: relative;
}
li div::before {
  content:'';
  position: absolute;
  top: 0;
  left: -2px;
  bottom: 50%;
  width: 0.75em;
  border: 2px solid #000;
  border-top: 0 none transparent;
  border-right: 0 none transparent;
}
ul > li:last-child {
  border-left: 2px solid transparent;
}
<ul>
  <li><div>Level 1</div></li>
  <li><div>Level 1</div>
    <ul>
      <li><div>Level 2</div></li>
      <li><div>Level 2</div>
        <ul>
          <li><div>Level 3</div></li>
          <li><div>Level 3</div></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><div>Level 1</div></li>
</ul>

We get this:

Link to the JS Fiddle demo.

JS Fiddle demo

like image 192
David Thomas Avatar answered Oct 28 '22 08:10

David Thomas