0

を使用して、1つのCSS宣言を複数のHTML要素に適用することは可能nth-childですか?

たとえば、ネストされたリストがあり、4つのCSS宣言のみを使用して、背景色を赤をリストアイテム1に、緑をリストアイテム2〜4に、青をリストアイテム5〜8に、黄色をリストアイテム9に適用したいとします。

<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>
4

2 に答える 2

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;
}

lin番目のアウターとそのすべてのサブに適用する式を探している場合は、次のliようになります。

/* Of course, substitute n with the actual number */
#nav > li:nth-child(n), #nav > li:nth-child(n) li
于 2012-05-11T17:41:29.257 に答える
0

サブグループ付き(あなたが持っているように)

さて、あなたの場合、それらはサブグループ化されているので簡単です。これは動作します。

#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;}

単一のリストの場合(他の人が持っているかもしれないように)

それがすべて1つのリストである場合も可能ですが、カスケードが役立つようにする必要があります。この例を参照してください

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;}  
于 2012-05-11T17:41:00.487 に答える