CSS, only affect the top lis of a ul?
I have a nested UL navigation list, with ul's contained inside some other li elements. here's the mark up:
<ul class="navigation">
<li><a href="#">No Chidren</a></li>
<li><a href="#">With Chilren</a>
<ul>
<li><a href="#">Child 1</a></li>
<li><a href="#">Child 2</a></li>
</ul>
</li>
</ul>
I tried styling it with some of the following CSS declarations:
.navigation {
//stylings
}
.navigation li{
//stylings
}
.navigation li a{
//stylings
}
.navigation li a:hover{
//stylings
}
but the .navigation li affects all of the list elements, including the children. is there a way to target the lis so that the sty开发者_如何学编程les are only applied to the top-level ones, and not the children?
As others have mentioned, the >
selector will only select direct children. However, this doesn't work in IE 6.
If you need to support IE 6, you can add a class to child ul
s or li
s, and use that to remove the styling cascading from the top li
:
<ul class="navigation">
<li><a href="#">No Chidren</a></li>
<li><a href="#">With Chilren</a>
<ul class="level1">
<li><a href="#">Child 1</a></li>
<li><a href="#">Child 2</a></li>
</ul>
</li>
</ul>
--
.navigation li{
background: url(bg.png);
}
.navigation .level1 li{
background: none;
}
Like this, the ">" states that the li must be a direct child of .navigation
.navigation {
//stylings
}
.navigation > li{
//stylings
}
.navigation > li a{
//stylings
}
.navigation > li a:hover{
//stylings
}
Yes, it is possible with child selectors.
.navigation>li>a{
//stylings
}
Code above will affect "No Chidren" and "With Chilren" link but not "child 1" element.
Here is working example: http://jsfiddle.net/VuNwX/
And here you can read more about selectors: http://css.maxdesign.com.au/selectutorial/index.htm
精彩评论