您可以浮动它们,只需对它们应用一个包装器,.box
这将允许您margin:auto;
相.box
对于浮动包装器。
CSS:
div.wrapper {
width:100%;
border:3px solid red;
}
div.clear {
clear:both;
}
div.box-wrapper {
float:left;
margin:10px 0;
height:100px;
width:20%;
}
div.box {
border:1px solid black;
width:80px;
height:100px;
margin:auto;
}
HTML:
<div class="wrapper">
<div class="box-wrapper"><div class="box"></div></div>
<div class="box-wrapper"><div class="box"></div></div>
<div class="box-wrapper"><div class="box"></div></div>
<div class="box-wrapper"><div class="box"></div></div>
<div class="box-wrapper"><div class="box"></div></div>
<div class="box-wrapper"><div class="box"></div></div>
<div class="box-wrapper"><div class="box"></div></div>
<div class="box-wrapper"><div class="box"></div></div>
<div class="box-wrapper"><div class="box"></div></div>
<div class="box-wrapper"><div class="box"></div></div>
<div class="clear"></div>
</div>
演示:http: //jsfiddle.net/2avwf/
为了小提琴窗口,我没有将它们设置为 200px 宽。只需将其换成width:80px
您想要的宽度即可。
如果你想让它成为一个动态的解决方案,其中一行中的盒子数量会根据用户的屏幕大小等而有所不同,只需制作 3 或 4 个宽度定义盒子包装类:
.box-wrapper-25 {
width:25%;
}
.box-wrapper-33 {
width:33%;
}
然后使用 JQuery,您可以轻松检测框包装器的宽度.wrapper
并将覆盖类分配给:
$('.box-wrapper').each(function(){
$(this).removeClass().addClass('box-wrapper box-wrapper-25'); // only need 4 per row
});
像这样的东西:http: //jsfiddle.net/RcDky/