I have a structure of nested lists and I am trying to style them with CSS. I want each level to be indented more than each previous one, but I want the top border for each list to extend all the way to the end of the parent list. Here is what I have:
<!DOCTYPE html>
<html><head>
<title>nested list test</title>
<style type="text/css">
ul, li {
margin: 0; padding: 0; list-style: none;
}
#outer {
width: 300px; border: solid black 2px;
}
#outer ul {
border-top: solid #bbbbbb 1px;
}
#outer > li > ul > li > span {
padding-left: 30px;
}
#outer > li > ul > li > ul > li > span {
padding-left: 60px;
}
</style>
</head>
<body>
<ul id="outer">
<li><span>Item 1</span></li>
<li><span>Item 2</span>
<ul>
<li><span>Item 2a</span></li>
<li><span>Item 2b</span>
<ul>
<li><span>Item 2b1</span></li>
开发者_如何学Go <li><span>Item 2b2</span>
<ul>
<li><span>Item 2b2a</span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</body></html>
You can see it at http://jsfiddle.net/pwaxQ/1/. It works fine when there are 3 levels but if I add a 4th, it breaks. I can add some more rules to make it work with 4 levels, but it will break if I add a 5th. And so on. I can easily make it work with Javascript, but I am wondering if there is a way to make this layout handle any depth, using CSS only, without having to come up with new rules.
You could do a little dance where each list, other than the outer list, has a left margin of -1000 and a left padding of +1030, so that the border extends far to the left, and the root list has overflow set to hidden. It still won't get arbitrarily deep, but you can increase the maximum number of levels by changing the numbers without adding extra rules.
I don't see how that can be done without explicit rules for each level. You can avoid having to chain the rules like that, however, at the cost of a little additional markup:
<!DOCTYPE html>
<html><head>
<title>nested list test</title>
<style type="text/css">
ul, li {
margin: 0; padding: 0; list-style: none;
}
#outer {
width: 300px; border: solid black 2px;
}
#outer ul {
border-top: solid #bbbbbb 1px;
}
#outer .level1 li > span { padding-left: 30px; }
#outer .level2 li > span { padding-left: 60px; }
#outer .level3 li > span { padding-left: 90px; }
</style>
</head>
<body>
<ul id="outer">
<li><span>Item 1</span></li>
<li><span>Item 2</span>
<ul class="level1">
<li><span>Item 2a</span></li>
<li><span>Item 2b</span>
<ul class="level2">
<li><span>Item 2b1</span></li>
<li><span>Item 2b2</span>
<ul class="level3">
<li><span>Item 2b2a</span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</body></html>
If you were using SASS, you could even do not very useful but cool stuff like this to loop through as many levels as you need:
!levels = 10
@for !i from 0 to !levels
#outer ul.level#{!i} > li
padding-left: #{!i*30}px
精彩评论