flex弹性盒子的使用方法
使行内元素并排排列得方法除了使用float浮动属性之外,还可以使用display的flex属性。具体使用方法如下:
.box1{
width: 800px;
border: 1px solid #bfa;
}
.box2{
width: 100px;
height: 100px;
background-color: yellow;
}
.box3{
width: 100px;
height: 100px;
background-color: green;
}
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
以上代码形成的效果如下图所示:
如果给box2和box3使用浮动效果,将两块元素横向排列,代码如下:
.box1{
width: 800px;
border: 1px solid #bfa;
}
.box2{
width: 100px;
height: 100px;
background-color: yellow;
float:left; //开启浮动
}
.box3{
width: 100px;
height: 100px;
background-color: green;
float:left; //开启浮动
}
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
可以看到产生了高度塌陷的效果。
如果改用flex属性,代码如下
.box1{
width: 800px;
border: 1px solid #bfa;
display:flex;
}
.box2{
width: 100px;
height: 100px;
background-color: yellow;
}
.box3{
width: 100px;
height: 100px;
background-color: green;
}
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
产生的效果如下图所示:
可以看到父级容器并没有产生高度塌陷的问题。
总结:flex弹性盒子模型功能类似于浮动效果,可将多个行内元素并行排列。
与浮动效果不同的是,使用float属性漂浮的元素会脱离文档流,产生高度塌陷得现象;
flex属性不会将元素脱离文档流,而是保持元素原有宽高得占位。
flex弹性盒子的几种重要属性
在了解属性之前,首先要了解以下flex的模型:
(图片来自阮一峰的个人文章:Flex布局教程—语法篇)
图中的:
main axis:表示主轴,
cross axis表示从轴(交叉轴),
item:表示项目
了解完flex的基本构成之后,可以开始介绍flex最常用的属性。
//设置项目在主轴上的排列方式:
justify-content:flex-start | flex-end | center | space-between | space-around;
(图片来自阮一峰的个人文章:Flex布局教程—语法篇)
值得注意的是,display:flex属性要添加在容纳项目的容器里,如:
.father{
display:flex;
justify-content:flex-start | flex-end | center | space-between | space-around;
}
参考文章:http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html
(阮一峰的个人文章:Flex布局教程—语法篇)