<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>
如何在纯CSS中为每个第二类视图设置样式。
在jquery我会做
$('*[class=views]:even').addClass('views');
但我怎么能做这个CSS?
答案 0 :(得分:20)
您可以使用:nth-child
属性:
示例:
.question_container:nth-child(2n) .views{
color: red;
}
:nth-child(2)
会选择 第二项,而:nth-child(2n)
会选择每个第二项。
答案 1 :(得分:0)
正如@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>
答案 2 :(得分:0)
那么你可以让盒子有一半(50%)吗? 将它们浮动到左侧然后清除将是最佳解决方案
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:
.box {
display: inline-block;
width: 50%;
float: left;
}
.clear {
clear: both;
}
这是一个小提琴: https://jsfiddle.net/r5xq9von/
答案 3 :(得分:0)
您可以将 :nth-child
选择器与 even
关键字一起使用。
.question_container:nth-child(even) .views{
/* styles for every second class */
}
对于选择奇数或偶数孩子的琐碎情况,我不会使用 :nth-child(1n)
或 :nth-child(2n)
。尽管它们完全有效,但不如关键字 odd
和 even
;特别适用于不每天使用 CSS 的人。