使用css表排列div

时间:2014-09-08 01:22:11

标签: html css

我有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;
}

2 个答案:

答案 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;
}