Html 如何仅使用 CSS(无 js)选择所有其他 div 类元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14986810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I select every other div class element using just CSS (no js)
提问by Jaime
I know how to do this using javascript and php, but I am trying to learn how/if it is possible to do this using just css.
我知道如何使用 javascript 和 php 来做到这一点,但我正在尝试学习如何/是否可以仅使用 css 来做到这一点。
I have a container which holds many items. Each item has a picture, and below it, a div containing a description. I want the background of the description to be different for every other item.
我有一个装有许多物品的容器。每个项目都有一张图片,其下方是一个包含说明的 div。我希望每个其他项目的描述背景都不同。
Is it possible to achieve this using just css? If so, how? I have been fooling around with using the selectors
是否可以仅使用 css 来实现这一点?如果是这样,如何?我一直在使用选择器
.item:nth-child(odd){background-color:red}
.item .description:nth-of-type(odd){background-color:orange;}
I can't seem to get it. Suggestions, comments, anything is appreciated.
Below is some simplified sample code that demonstrates what I have going on.
我似乎无法得到它。建议,评论,任何东西都表示赞赏。
下面是一些简化的示例代码,演示了我正在做的事情。
<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>
回答by ThinkingStiff
回答by Eric Goncalves
.item:nth-child(even) {...}
.item:nth-child(odd) {...}
回答by Sourceforest
Maybe it's possible when we use this:
也许当我们使用它时是可能的:
.item:nth-of-type(odd) .description{background-color:orange;}
or
或者
.item:nth-child(odd) .description{background-color:orange;}
You can see my screenshots: http://screencast.com/t/17g9joVj8Z
I hope you get what you need.
你可以看到我的截图:http: //screencast.com/t/17g9joVj8Z
我希望你得到你需要的。
回答by starowere
you should set nth-of-type to .item element:
您应该将 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;}