简体   繁体   English

CSS,只影响ul的顶级lis?

[英]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. 我有一个嵌套的UL导航列表,其中包含一些其他li元素。 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: 我尝试使用以下一些CSS声明来设置样式:

.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. 但.navigation li会影响所有列表元素,包括子元素。 is there a way to target the lis so that the styles are only applied to the top-level ones, and not the children? 有没有办法定位lis,以便样式只适用于顶级的,而不是孩子?

As others have mentioned, the > selector will only select direct children. 正如其他人所提到的, >选择器只会选择直接子项。 However, this doesn't work in IE 6 . 但是,这在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 : 如果你需要支持IE 6,你可以添加一个类给子ulli s,并使用它来删除顶部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 像这样,“>”表示li必须是.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. 上面的代码将影响“No Chidren”和“With Chilren”链接,但不影响“child 1”元素。

Here is working example: http://jsfiddle.net/VuNwX/ 以下是工作示例: http//jsfiddle.net/VuNwX/

And here you can read more about selectors: http://css.maxdesign.com.au/selectutorial/index.htm 在这里,您可以阅读有关选择器的更多信息: http//css.maxdesign.com.au/selectutorial/index.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM