开发者社区> 问答> 正文

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

如何用CSS实现div之间自动分配宽度?我搜索了很多资料,但仍旧没有找到解决方法。

我创建了一个主div,宽度为100%,在内部又分成若干个div。大家可以看一下代码:http://jsfiddle.net/EAkLb/1/点击预览

HTML

<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自动分配,而不是手动去调试。

我自己写的代码实现的效果却是下图所示,中间的宽度不一致。

展开
收起
a123456678 2016-03-25 14:24:18 3900 0
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%;
    }
    2019-07-17 19:14:18
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
零基础CSS入门教程 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载