CSS 如果每个元素都嵌入到另一个元素中,我如何获得每个第二个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10930385/
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 can I get every second element if each is embedded in another one?
提问by yehuda
<div class="question_container">
<div class="views">
<div>10</div>
</div>
<div>Something else</div>
</div>
<div class="question_container">
<div class="views">
<div>10</div>
</div>
<div>Something else</div>
</div>
<div class="question_container">
<div class="views">
<div>10</div>
</div>
<div>Something else</div>
</div>
How can I style every second class views in pure css.
如何在纯 css 中设置每隔一个类视图的样式。
In jquery I would do
在 jquery 我会做
$('*[class=views]:even').addClass('views');
But how can I do this CSS?
但是我该如何做这个 CSS?
回答by sandeep
You can use the :nth-child
property for this:
您可以:nth-child
为此使用该属性:
Example:
例子:
.question_container:nth-child(2n) .views{
color: red;
}
:nth-child(2)
would select onlythe second item, while :nth-child(2n)
will select everysecond item.
:nth-child(2)
将只选择第二个项目,而:nth-child(2n)
将选择每隔一个项目。
回答by Mike
As @Andrej and @sandeep said, it does work:
正如@Andrej 和@sandeep 所说,它确实有效:
<style>
.question_container:nth-child(2n) .views{
color: red;
}
</style>
<div class="question_container">
<div class="views">
<div>10</div>
</div>
<div>Something else</div>
</div>
<div class="question_container">
<div class="views">
<div>10</div>
</div>
<div>Something else</div>
</div>
<div class="question_container">
<div class="views">
<div>10</div>
</div>
<div>Something else</div>
</div>
回答by MRadev
Well you can make the box to be have half the widht (50%) ? Having them floated to the left and then clear will be the best solution
那么你可以让盒子有一半的宽度(50%)?让它们漂浮到左边然后清除将是最好的解决方案
HTML:
HTML:
<div class="legend-box">
<div class="box"> [] box 1 </div>
<div class="box"> [] box 2 </div>
<div class="box"> [] box 3 </div>
<div class="box"> [] box 4 </div>
<div class="box"> [] box 5 </div>
<div class="box"> [] box 6 </div>
<div class="clear"></div>
</div>
CSS:
CSS:
.box {
display: inline-block;
width: 50%;
float: left;
}
.clear {
clear: both;
}
Here is a fiddle: https://jsfiddle.net/r5xq9von/
这是一个小提琴:https: //jsfiddle.net/r5xq9von/