固定列数的动态单元格数

时间:2012-12-26 16:13:03

标签: html css layout

是否可以在具有固定列数(例如4)的容器内分配动态数量的单元格。我想做的是:

<div class="container_4">
    <div class="cell">Cell 1</div>
    <div class="cell">Cell 2</div>
    <div class="cell">Cell 3</div>
    <div class="cell">Cell 4</div>
    <div class="cell">Cell 5</div>
    <div class="cell">Cell 6</div>
    <div class="cell">Cell 7</div>
</div>

没有指定每4个单元格后行结束的位置,这应该是:

Cell 1    Cell 2    Cell 3    Cell 4
Cell 5    Cell 6    Cell 7

2 个答案:

答案 0 :(得分:4)

如果我做对了,这可能适合你:

#container_4 {
    width: 400px; /* Change to your container width */
}

.cell {
    width: 25%; /* Use different percentages for a different number of columns */
    float: left;
}

然后,如果您的细胞需要边距,或者进行数学计算,例如:

.cell {
    width: 23%; /* 1/4 the container width - margin x 2 */
    margin: 1%; /* Your margin */
    float: left;
}

或者使用CSS3属性box-sizing并使用填充代替您的框边距:

.cell {
    width: 25%;
    padding: 1%;
    float: left;
    /* This will make the specified with include padding's and borders */
    box-sizing: border-box; /* Standard syntax */
    -moz-box-sizing: border-box; /* Firefox */
    -webkit-box-sizing: border-box; /* Safari */
}

注意:box-sizing属性不适用于 ie7 。在怪癖模式下, ie6 使用默认的“border-box”模型(有关ie6 box model bug的更多信息,请参阅here)。

答案 1 :(得分:1)

CSS

.container_4{
width:480px;
height:160px;
background:#EFEFEF;
}

.cell{
border:solid 1px #999;
float:left;
height:58px;
margin-left:10px;
margin-top:10px;
width:98px;
background-color:White;
}

DEMO HERE

相关问题