在前端开发中一些列表我们经常需要设置浮动和间距margin来使他们他们显示在一行(类似首页的最新文章),但有时候老是要考虑到他们的间距和在父元素的显示是否居中,有没有一种简单的方法呢?答案是肯定的,一次看某个网页的源码时看到了一种新的方法。
把这些小盒子设置display为inline-block,父级元素中设置text-align为justify(设置字体方向为两端对齐),这样那些小盒子就会自动两端对齐了,但前提是一行里已经放不下父元素里所有的内容,假设有三个盒子,而每个盒子的宽度为30%,这三个盒子能在一行里显示,就看到自动间距的效果。
这种我们可以再最后加个div设置它的宽度为100%、高度为0;于是得到下面的代码。
/*
**css
*/
.content{
width:95%;
margin:0 auto;
text-align:justify;
}
.box{
display:inline-block;
width:30%;
height:260px;
margin-top:20px;
background:#000;
}
<!-- HTML -->
<div class="content">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div style="width:100%;height:0;"></div>
</div>
上面的方案貌似没问题,但是很快我们会发现当有五个元素的时候,第二行显示的间距不和第一行对齐,这是由于第二行只有两个元素,字体方向为两端对齐,所以自然就在第二行等距离分布了。这时我们得对代码做一下优化,在最后面的<div>改为与box等宽度的div数量增加为每行显示的box的数量。
最终代码
/*
**css
*/
.content{
width:95%;
margin:0 auto;
text-align:justify;
}
.box{
display:inline-block;
width:30%;
height:260px;
margin-top:20px;
background:#000;
}
.just-div{
width:30%;
height:0;
}
<!-- HTML -->
<div class="content">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="just-div"></div>
<div class="just-div"></div>
<div class="just-div"></div>
</div>