2013-02-20 44 views
31

非常感謝您提前給出的答覆。如何使用CSS選擇每個其他div類元素(無js)

我知道如何做到這一點使用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> 

回答

42

你想在.itemnth-child()

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

演示:jsFiddle

+0

非常感謝! :) 令人敬畏的貓,哈哈 – Jaime 2013-02-20 18:15:02

+3

這是行不通的。你不能按類選擇nth-child,只能通過元素類型。如果你添加另一個班與另一個班的賠率和平衡將全部轉移。 – 2016-04-08 11:00:09

+0

我同意@WalturBuerk。我已經嘗試過這種方式,並且對不一致的結果感到困惑,只有意識到有時候我有一個與此僞選擇器中計數的不同類的兄弟姐妹。遊民。 – 2016-09-28 23:44:13

0

你應該設置第n-的類型來.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;} 
2

也許這是可能的,當我們使用此:

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

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

你可以看到我的截圖:http://screencast.com/t/17g9joVj8Z
我希望你得到你所需要的。

相關問題