Ashley Sheridan​

Nested Lists with Overriding Styles

Posted on

Nested tree menus are often a useful way of portraying hierarchical data, and are most commonly used to display directory trees to a user. Semantically, the best way to create them is with proper list markup. The problem with nested lists, is that, by default, they all have the same amount of padding, which is often annoying for the topmost list item.

What might seem an obvious solution is not the most elegant. Most people would go for a class on the top-most list to style that differently from the others. While there is no real problem with that, this solution is far more elegant, and can lend itself to a variety of other techniques of nested elements. Consider the following HTML:

<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3 <ul> <li>Item 3.1</li> <li>Item 3.2</li> <li>Item 3.3 <ul> <li>Item 3.3.1</li> <li>Item 3.3.2</li> </ul> </li> </ul> </li> <li>Item 4 <ul> <li>Item 4.1</li> <li>Item 4.2</li> </ul> </li> </ul>

The CSS to go with this will look like the following:

ul { padding-left: 0px; } ul ul { padding-left: 30px; } li { list-style-image: url('../img/folder.png'); list-style-position: inside; } ul ul li { list-style-image: url('/img/folder-blue.png'); } ul ul ul li { list-style-image: url('/img/folder-green.png'); }

The end result will look like this:

  • Item 1
  • Item 2
  • Item 3
    • Item 3.1
    • Item 3.2
    • Item 3.3
      • Item 3.3.1
      • Item 3.3.2
  • Item 4
    • Item 4.1
    • Item 4.2

The key here is the selector used in the CSS. Basically, I set one style for all the <ul> tags, and then another for any <ul> tags that exist within another <ul> tag! There are literally so many ways you can use this technique of nested tags in CSS. I've used it myself for things like these nested lists and rounded corner boxes.