布局的传统解决方案,基于盒状模型,依赖 display 属性 + position属性 + float属性。它对于那些特殊布局非常不方便,比如,垂直居中就不容易实现。W3C 提出了一种新的方案----Flex 布局,可以简便、完整、响应式地实现各种页面布局。目前,它已经得到了所有浏览器的支持,这意味着,现在就能很安全地使用这项功能
如图所示
弹性盒子外容器常用属性
属性 | 描述 |
flex-direction | 指定弹性容器中子元素排列方式 |
flex-wrap | 设置弹性盒子的子元素超出父容器时是否换行 |
flex-flow | flex-direction 和 flex-wrap 的简写 |
align-items | 设置弹性盒子元素在侧轴(纵轴)方向上的对齐方式 |
align-content | 修改 flex-wrap 属性的行为,类似 align-items, 但不是设置子元素对齐,而是设置行对齐 |
justify-content | 设置弹性盒子元素在主轴(横轴)方向上的对齐方式 |
1. flex-direction 属性
决定项目的方向。注意:如果元素不是弹性盒对象的元素,则 flex-direction 属性不起作用。
.flex-container { flex-direction: row | row-reverse | column | column-reverse; }
值 | 描述 |
row | 默认值。元素将水平显示,一个行一样。 |
row-reverse | 与 row 相同,但是以相反的顺序。 |
column | 元素将垂直显示,一个列一样。 |
column-reverse | 与 column 相同,但是以相反的顺序。 |
2. flex-wrap 属性
flex-wrap 属性规定flex容器是单行或者多行,同时横轴的方向决定了新行堆叠的方向。
.flex-container { flex-wrap: nowrap | wrap | wrap-reverse; }
值 | 描述 |
nowrap | 默认值。规定元素不拆行或不拆列。 |
wrap | 规定元素在必要的时候拆行或拆列。 |
wrap-reverse | 规定元素在必要的时候拆行或拆列,但是以相反的顺序。 |
3. flex-flow 属性
flex-flow属性是flex-direction属性和flex-wrap属性的简写形式,默认值为row nowrap。
.flex-container { flex-flow: flex-direction | flex-wrap }
4. align-items属性
align-items 属性定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。
.flex-container {align-items: flex-start | flex-end | center | stretch | baseline; }
值 | 描述 |
flex-start | 项目位于容器的开头。 |
flex-end | 项目位于容器的结尾。 |
center | 项目位于容器的中心。 |
stretch | 默认值。项目被拉伸以适应容器。 |
baseline | 项目位于容器的基线上。 |
5. justify-content属性
justify-content 用于设置或检索弹性盒子元素在主轴(横轴)方向上的对齐方式。
.flex-container {justify-content: flex-start | flex-end | center | space-between | space-around; }
值 | 描述 |
flex-start | 项目位于容器的开头。 |
flex-end | 项目位于容器的结尾。 |
center | 项目位于容器的中心。 |
space-between | 项目位于各行之间留有空白的容器内。 |
space-around | 项目位于各行之前、之间、之后都留有空白的容器内。 |