如何用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自动分配,而不是手动去调试。
我自己写的代码实现的效果却是下图所示,中间的宽度不一致。
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%;
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。