使用nth:child将CSS声明应用于多个元素

时间:2012-05-11 17:34:48

标签: css css3 css-selectors

是否可以使用nth-child将一个CSS声明应用于多个HTML元素?

例如,我有一个嵌套列表,我想将背景颜色红色应用于列表项目1,绿色列表项目2到4,蓝色列表项目5到8,黄色列表项目9仅使用4个CSS声明。

<ul id="nav">
  <li><a href="#">Home</a></li>
  <li><a href="#">About</a>
      <ul>
         <li><a href="#">Our Team</a></li>
         <li><a href="#">Our Goal</a></li>
      </ul>
  </li>
  <li><a href="#">Media</a>
      <ul>
         <li><a href="#">NLC in the News</a></li>
         <li><a href="#">Photos</a></li>
         <li><a href="#">Videos</a></li>
      </ul>
  </li>
  <li><a href="#">Events</a></li>
</ul>

2 个答案:

答案 0 :(得分:3)

我在这里看到4个外li元素(主页,关于,媒体,事件)。如果这些对应于您所指的4个CSS声明(实际上是规则),那么:nth-child()只是解决方案的一部分:

#nav > li:nth-child(1) {
    background-color: red;
}

#nav > li:nth-child(2), #nav > li:nth-child(2) li {
    background-color: green;
}

#nav > li:nth-child(3), #nav > li:nth-child(3) li {
    background-color: blue;
}

#nav > li:nth-child(4) {
    background-color: yellow;
}

如果您正在寻找适用于第n个外li及其所有子li的公式,那么就是这样:

/* Of course, substitute n with the actual number */
#nav > li:nth-child(n), #nav > li:nth-child(n) li

答案 1 :(得分:0)

使用子组(与您一样)

嗯,在你的情况下,它更容易,因为它们是subgrouped。 This works

#nav > li:nth-child(1) {background-color: red;}
#nav > li:nth-child(2), 
#nav > li:nth-child(2) > ul > li {background-color: green;}
#nav > li:nth-child(3), 
#nav > li:nth-child(3) > ul > li {background-color: blue;}
#nav > li:nth-child(4) {background-color: yellow;}

单个列表(与其他人一样)

如果它只是一个列表也是可能的,但您需要允许级联帮助。 See this example

<强> HTML

<ul id="nav"> 
  <li><a href="#">Home</a></li> 
  <li><a href="#">About</a></li> 
  <li><a href="#">Our Team</a></li> 
  <li><a href="#">Our Goal</a></li> 
  <li><a href="#">Media</a></li> 
  <li><a href="#">NLC in the News</a></li> 
  <li><a href="#">Photos</a></li> 
  <li><a href="#">Videos</a></li>   
  <li><a href="#">Events</a></li> 
</ul>

<强> CSS

#nav > li:nth-child(1) {background-color: red;} 
#nav > li:nth-child(n+2) {background-color: green;} 
#nav > li:nth-child(n+5) {background-color: blue;} 
#nav > li:nth-child(n+9) {background-color: yellow;}  
相关问题