Horizontal Nested List using CSS

user151419 picture user151419 · Dec 4, 2010 · Viewed 7.4k times · Source

I'm trying to create a horizontal list from a nested list markup, as an example I have the current markup:

<ul>
<li class="alone">List Item 1</li>
<li class="alone">List Item 2</li>
<li class="alone">List Item 3</li>
<li class="group">List Item 4
  <ul>
    <li class="not_alone">List Item 4a</li>
    <li class="not_alone">List Item 4b</li>
    <li class="not_alone">List Item 4c</li>
    <li class="not_alone">List Item 4d</li>
  </ul>
</li>
<li class="alone">List Item 5</li>
</ul>

I would like to achieve something similar to this:

<style>
div { display: inline-block; }
.alone { background: #E5ECF9; border: 1px solid #336699; color: #336699;  }
.group { background: #FBE3E4; border: 1px solid #CC0000; color: #CC0000; }
.group .not_alone { background: #FBE3E4; border: 1px solid #CC0000; color: #CC0000; }
.item { padding: 2px; margin: 0 2px; }
</style>
<div class="wrapper">
  <div class="alone item">List Item 1</div>
  <div class="alone item">List Item 2</div>
  <div class="alone item">List Item 3</div>
  <div class="group item">
    List Item 4
    <div class="group item">List Item 4a</div>
    <div class="group item">List Item 4b</div>
    <div class="group item">List Item 4c</div>
    <div class="group item">List Item 4d</div>
  </div>
  </div>
  <div class="alone item">List Item 5</div>
</div>

You can see a demo here http://jsbin.com/exivi5.

Is this possible using the existing nested list markup? Also, can I also keep the width of the ul parent list to 100% so it fits the entire viewport?

This needs to be compatible in FF, Webkit and IE7+ but will settle for IE8+ support.

Thanks in advance!

Answer

Lucius picture Lucius · Dec 4, 2010

try adding these css rules:

ul {list-style: none; margin: 0; padding: 0; float:left; display: inline;}
ul li {float:left; display: inline; margin: 0 5px; padding: 3px 2px;}
ul li ul {float:right;}
h2 {clear: left;}

with a bit of fiddling with margins & paddings it should look the same as yours