一、定义
是一种当页面需要适应不同屏幕大小及设备类型时确保元素有恰当的行为的布局方式。
引入弹性盒布局模型的目的是提供一种更加有效的方式来对一个容器中的子元素进行排列、对和分配空白空间。
二、内容
弹性盒子由弹性容器和弹性子元素构成。
弹性容器通过display属性的值flex将其定义为弹性容器。
弹性容器内包含一个或多个弹性子元素。
- 默认弹性盒子的内容是横向拜访的。
.container{
width: 500px;
height: 500px;
background-color: cadetblue;
}
.box1{
width: 100px;
height: 100px;
background-color: red;
}
.box2{
width: 100px;
height: 100px;
background-color: green;
}
.box3{
width: 100px;
height: 100px;
background-color: blue;
}
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
下图未使用display:flex;
下图使用了dispaly:flex;
.container{
width: 500px;
height: 500px;
background-color: cadetblue;
display: flex;
}
- flex-direction属性指定了弹性元素在父元素中的位置
row(横向到竖向排列左对齐)
row-reverse(反向横向排列右对齐,从后往前排,最后一排在最前列)
column(纵向排列)
column-reverse(反纵向排列,从后往前排,最后一排在最上面)
flex-direction: row;
flex-direction: row-reverse;
flex-direction: column;
flex-direction: column-reverse;
- justify-content属性:应用在弹性容器上,把弹性项沿弹性的主轴线对齐。(垂直方向,上下居中)
flex-start(靠上摆放)
flex-end(靠下摆放)
center(靠中间排放)
flex-direction: column;
justify-content: start;
flex-direction: column;
justify-content: end;
flex-direction: column;
justify-content: center;
- align-items属性指定了弹性元素在父元素中的位置(横方向,左右居中)
flex-start(靠左摆放)
flex-end(靠右摆放)
center(靠中间排放)
子元素上的属性
- flexgrow/flex:子物体分别设定权重在父盒子里分配,此刻width和height无作用了。
.container{
width: 500px;
height: 500px;
background-color: cadetblue;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.box1{
width: 100px;
height: 100px;
background-color: red;
flex-grow: 2;
}
.box2{
width: 100px;
height: 100px;
background-color: green;
flex-grow: 1;
}
.box3{
width: 100px;
height: 100px;
background-color: blue;
flex-grow: 1;
}