弹性盒布局
flex是Flexinle Box的缩写,意思就是弹性布局,使用flex进行布局的方式,就叫做弹性盒布局。
flex的基本概念
设定了display:flex属性的容器,默认从左上方有两条轴线,x轴即水平轴(main axis)和y轴(corss axis),其被称为flex容器,其子元素被称为容器项目。
flex容器里面的项目默认为横向排列。
<div style="display: flex;background: #f0f;width: 400px;height: 200px;">
<div style="width: 100px;height: 80px;background: #0f0;"></div>
<div style="width: 100px;height: 80px;background: #ff0;"></div>
<div style="width: 100px;height: 80px;background: #0ff;"></div>
</div>
弹性盒的排列方式
如果想要改变弹性盒内元素的排列方式,可以为其添加:
flex-direction属性。它有四个属性值
- row(默认值)
- row-reverse(反转横向排列)
- column(自上而下)
- column-reverse(自下而上)
<div style="display: flex;background: #f0f;width: 400px;height: 200px;flex-direction: column;">
<div style="width: 100px;height: 80px;background: #0f0;"></div>
<div style="width: 100px;height: 80px;background: #ff0;"></div>
<div style="width: 100px;height: 80px;background: #0ff;"></div>
</div>
弹性盒的对齐方式
主轴对齐方式(x)
justify-content属性应用在容器上,可以改变它内部项目横向的排列方式它有五个属性值
- flex-start 默认属性,左对齐
- flex-end 右对齐
- center 居中对齐
- space-between 两端对齐,间距自动分配
- space-around:自动分配间距,两端间距是中间的一半
侧轴对齐方式(y)
align-items属性可以改变弹性盒的侧轴对齐方式,它有五个属性值
- flex-start 顶端对齐
- flex-end 底部对齐
- center 垂直居中对齐
- baseline 项目内文本低对齐
- stretch 默认值,项目的高度自适应容器的高度
注:如果对弹性盒使用flex-direction:column或
flex-direction:column-reverse 属性时,弹性盒的横轴和纵轴会发生改变,及横轴为y轴,纵轴为x轴
设置flex的行数
flex-wrap可以设置弹性盒里面内容的纵向排列方式它与三个属性值:
- nowrap: flex容器为单行容器;
- wrap: flex容器为多行并且自上而下排列;
- wrap-reverse: flex容器为多行并且自下而上排列;
设置行与行之间的对齐方式
当弹性盒容器的侧轴还有多余的空间时,可以用align-content属性来调整对齐方式,该属性对单行容器无效;
align-content有五个属性值:
- flex-start 没有行间距
- flex-end 低对齐,没有行间距
- center 居中没有行间距
- space-between 上下两端对齐,剩余行距自动分配
- space-around 自动分配行距,上下距容器的间距是中间行距的1/2;