我有4个div
元素,我需要将前两个元素排成一行,接下来的两个元素排在第二行。div
元素正在循环中生成,所以不能单独访问每个。所以,我尝试使用:nth-child
属性,但无法解决它。这是代码的一个例子。 JSFIDDLE
HTML
<div class="relatedposts">
<div class="relatedthumb">
<img src="http://placekitten.com/120/60" ><br>
<p>Post to check the page builder plugin</p>
</div>
<div class="relatedthumb">
<img src="http://placekitten.com/120/60" ><br>
<p>Post to check the page builder plugin and now the second line here ok
</div>
<div class="relatedthumb">
<img src="http://placekitten.com/120/60" ><br>
<p>Post to check the page builder plugin</p>
</div>
<div class="relatedthumb">
<img src="http://placekitten.com/120/60" ><br>
<p>Post to check the page builder plugindskjnfkdjndskjcndskjcndsk
</div>
CSS
.relatedposts{display:table;}
.relatedthumb {
display: inline-block;
width:40%;
}
.relatedthumb img{text-align:center;}
div.relatedthumb:nth-child(2n+1){
display:table-row;
}
答案 0 :(得分:1)
你不需要CSS表格。
我updated your code to use floats & clear而非CSS表:
.relatedposts {
display:table;
}
.relatedthumb {
width:40%;
float: left;
}
.relatedthumb img {
text-align:center;
}
div.relatedthumb:nth-child(2n+1) {
clear: left;
}
答案 1 :(得分:1)
您刚刚将CSS属性分配给了错误的div。将它分配给父div并且它可以工作。
div.relatedposts:nth-child(2n+1){
display:table-row;
}