我知道如何使用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>
.item:nth-child(even) {...}
.item:nth-child(odd) {...}
也许当我们使用这个时有可能:
.item:nth-of-type(odd) .description{background-color:orange;}
或
.item:nth-child(odd) .description{background-color:orange;}
您可以看到我的屏幕截图:http://screencast.com/t/17g9joVj8Z我希望您能得到所需的东西。
您应该将.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;}