使用CSS实现div水平间距值的自动匹配

如何用CSS实现div之间自动分配宽度?我搜索了很多资料,但仍旧没有找到解决方法。
我创建了一个主div,宽度为100%,在内部又分成若干个div。大家可以看一下代码:http://jsfiddle.net/EAkLb/1/
HTML

<div class="section_zone">
    <div class="box_frame" id="_15">inner box 1</div>
    <div class="box_frame" id="_15">inner box 2</div>
    <div class="box_frame" id="_15">inner box 3</div>
    <div class="box_frame" id="_15">inner box 4</div>

CSS

iv.section_zone{
    margin: 0 auto;
    padding: 3px;
    width: 80%;   
    position: relative;
    overflow: auto;
    text-align: center;
    display: inline-block;
    clear: both;
    background-color: #fff;
    border: 1px solid #000;
    /* change border to be inside the box */
    box-sizing:border-box;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
}
div.box_frame{
    float: left;
    background-color: #eee; /* standard background color */
    border: 1px solid #898989; 
    border-radius: 11px;
    padding: 2px;
    margin: 0 5px;
    text-align: center;
    /* change border to be inside the box */
    box-sizing:border-box;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
}
div.box_frame:first-child{
    margin-left: 0;
}
div.box_frame:last-child{
    margin-right: 0;
    float: right;
}
div.box_frame#_15{ /* width 15% */
    width: 20%;
}

我需要将内部的div之间留存相同的宽度。第一个div是左对齐,最后一个div同样是右对齐,中间的相互之间的宽度统一。需要用CSS自动分配,而不是手动去调试。
我自己写的代码实现的效果却是下图所示,中间的宽度不一致。
请输入图片描述

我想达成的效果如下图所示:
请输入图片描述
请输入图片描述

请注意:目前,我的代码是显示4个div,我希望解决方法可以支持不同的数量,比如2个,3个,4个等等。

原问题:auto space between horizontal divs in CSS

阅读 8.7k
1 个回答

回答
Nicholas Hazel:首先,在一个HTML页面中使用相同ID的次数尽量为一。其次,你要确保div是在正确的位置上。对每个元素使用margin-right定义右边距,然后再针对最后一个div添加 psuedo-class,设置margin为0。
还有一种好办法适用于任何数量的div,用百分比来划分宽度,比如25%,33%。
代码demo:http://jsfiddle.net/EAkLb/5/
Css

* {
    margin:0;
    padding:0;
}
div.wrapper{
    width:100%;
    position:relative;
}
ul {
    position:relative;
    width:100%;
}
ul li {
    width:20%;
    float:left;
    padding:2.5%;
    background:#CCC;
    list-style:none;
    text-align:center;
}

bendtherules:假设100%的宽度中有4个区域,每个div宽度为22%,4个区域意味着有3个间距。你可以先做一个计算,22*4=88,100-88=12,12/3=4。这就计算出,每个div之间的宽度为4%。这种方法适用于较少的div。
CSS

div.box_frame{
    float: left;
    background-color: #eee; /* standard background color */
    border: 1px solid #898989; 
    border-radius: 11px;
    padding: 2px;
    margin-left:4%;
    text-align: center;
    /* change border to be inside the box */
    box-sizing:border-box;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
}
div.box_frame:first-child{
    margin-left: 0;
}
div.box_frame#_15{ /* width 15% */
    width: 22%;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题