Html 选择每 4 个 <div>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16948286/
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
Selecting every 4th <div>
提问by Craig Jonathan Kristensen
I have a long line of DIVs and I need to change the padding on every 4th DIV using the nth-child selector, but I am having problems getting it to work at all.
我有很长的 DIV 行,我需要使用第 n 个子选择器更改每 4 个 DIV 的填充,但是我在让它工作时遇到了问题。
Here is my css:
这是我的CSS:
.content_tab {
width: 220px;
height: 340px;
margin-right: 20px;
margin-bottom: 20px;
float: left;
background-color: #0F0;
}
.content_tab:nth-child(4){
background-color: #F00;
margin-right: 0px;
}
and here is my HTML:
这是我的 HTML:
<div class="content">
<div class="content_tab"></div>
<div class="content_tab"></div>
<div class="content_tab"></div>
<div class="content_tab"></div>
<div class="content_tab"></div>
<div class="content_tab"></div>
<div class="content_tab"></div>
</div>
Any ideas?
有任何想法吗?
回答by Pevara
You should change
你应该改变
.content_tab:nth-child(4){
To
到
.content_tab:nth-child(4n){
As explained here http://css-tricks.com/how-nth-child-works/
正如这里所解释的http://css-tricks.com/how-nth-child-works/
Or if you do not want the first div to be selected, you need
或者,如果您不想选择第一个 div,则需要
.content_tab:nth-child(4n+4){
回答by adrift
.content div:nth-child(4n) { /* selects 4, 8, 12, 16, etc. */
padding: 10px;
}
Or if you want every fourth element starting from the firstyou can use:
或者,如果您希望从第一个元素开始每第四个元素,您可以使用:
.content div:nth-child(4n + 1) { /* selects 1, 5, 9, 13 .. */
padding: 10px;
}
回答by Rory McCrossan
To get every 4th element in the selector use 4n
要获取选择器中的每 4 个元素,请使用 4n
.content_tab:nth-child(4n){
background-color: #F00;
margin-right: 0px;
}
Note I made the div sizes smaller in the fiddle so it was easier to see it working.
注意我在小提琴中缩小了 div 的大小,所以更容易看到它的工作。