46

私はjavascriptとphpを使用してこれを行う方法を知っていますが、cssだけを使用してこれを行うことができるかどうかを学習しようとしています。

たくさんのアイテムが入ったコンテナがあります。各アイテムには画像があり、その下には説明を含むdivがあります。説明の背景は、他のすべてのアイテムで異なるようにしたいです。

cssだけを使用してこれを達成することは可能ですか?もしそうなら、どのように?私はセレクターを使って浮気してきました

.item:nth-child(odd){background-color:red}
.item .description:nth-of-type(odd){background-color:orange;}

わからないようです。提案、コメント、何でもありがたいです。
以下は、私が行っていることを示すいくつかの簡略化されたサンプルコードです。

<style>
#container{width:100% height:100%;}
.item {float:left; width:250px; height:700px;}
.item img {width:250px; height:250px; float:left;}
.description {width:250px; height:450px; float:left; background-color:blue;}
.description:nth-of-type(even){background-color:red;}      // <- Here's the line!!
</style>

<html>
 <body>
  <div id="container">
   <div class="item">       //item 1
    <img src="image.jpg"/>
    <div class="description"> //This (and every odd number) I want to be blue 
     <h1>Title</h1>
     <h2>Sub Title</h2>
     <p>Lorem Ipsum dolor sit for Adun!</p>
     <a href="#">::LEARN MORE::</a>
    </div>
   </div>
   <div class="item">      //item 2 and so on...
    <img src="image.jpg"/>
    <div class="description"> //and this (and every even number, red)
     <h1>Title</h1>
     <h2>Sub Title</h2>
     <p>Lorem Ipsum dolor sit for Adun!</p>
     <a href="#">::LEARN MORE::</a>
    </div>
   </div>
  </div>
 <body>
</html>
4

4 に答える 4

69

あなたがnth-child()したい.item

.item:nth-child(odd) .description {
    background-color: red;
}

デモ: jsFiddle

于 2013-02-20T18:08:18.807 に答える
9
.item:nth-child(even) {...}
.item:nth-child(odd) {...}

デモ: http: //jsfiddle.net/DuL24/1/

于 2013-02-20T18:09:13.763 に答える
2

これを使用すると、おそらく可能です。

.item:nth-of-type(odd)  .description{background-color:orange;}  

また

.item:nth-child(odd) .description{background-color:orange;}

あなたは私のスクリーンショットを見ることができます:http
://screencast.com/t/17g9joVj8Z 私はあなたがあなたが必要とするものを手に入れることを望みます。

于 2013-02-20T19:09:43.493 に答える
0

nth-of-typeを.item要素に設定する必要があります。

#container{width:100% height:100%;}
.item {float:left; width:250px; height:700px;}
.item img {width:250px; height:250px; float:left;}
.description {width:250px; height:450px; float:left; background-color:blue;}
.item:nth-of-type(even) .description {background-color:red;} 
于 2013-02-20T18:13:31.493 に答える