float:left,display:-webkit-box,display:flex的区别
float:left,display:-webkit-box,display:flex都可以实现元素横向排列,但是却存在的一定的区别:
HTML代码:
<div id="box">
<div class="inner">1</div>
<div class="inner">2</div>
<div class="inner">3</div>
<div class="inner">4</div>
<div class="inner">5</div>
</div>
- float:left
#box{
width:400px;
height:300px;
border:1px solid;
position:absolute;
margin:auto;
top:0;
left:0;
right:0;
bottom:0
}
#box > .inner{
width:50px;
height:50px;
background:red;
font:20px/50px "微软雅黑";
text-align:center;
border:1px solid blue;
box-sizing:border-box;
float:left
}
页面效果:
如果我们把父元素#box的宽度变小:
#box{
width:100px;
height:300px;
border:1px solid;
position:absolute;
margin:auto;
top:0;
left:0;
right:0;
bottom:0
}
页面效果:
可以看见设置float:left,父元素的外框宽度小于子元素总体宽度的时候,元素会换行依次横向排列。
- display:-webkit-box
#box{
width:100px;
height:300px;
border:1px solid;
position:absolute;
margin:auto;
top:0;
left:0;
right:0;
bottom:0;
display:-webkit-box
}
#box > .inner{
width:50px;
height:50px;
background:red;
font:20px/50px "微软雅黑";
text-align:center;
border:1px solid blue;
box-sizing:border-box;
}
页面效果:
可以看见设置display:-webkit-box,父元素的外框宽度小于子元素总体宽度的时候,元素会横向排序并且溢出。
- display:flex
#box{
width:100px;
height:300px;
border:1px solid;
position:absolute;
margin:auto;
top:0;
left:0;
right:0;
bottom:0;
display:flex
}
#box > .inner{
width:50px;
height:50px;
background:red;
font:20px/50px "微软雅黑";
text-align:center;
border:1px solid blue;
box-sizing:border-box;
}
页面效果:
可以看见设置display:flex,父元素的外框宽度小于子元素总体宽度的时候,子元素会在父元素的宽度基础上,自动调节自身的宽度,把多余的挤掉,实现横向排列。