Flexbox 是什么?
Flexbox 是 CSS3 新增的布局模式,简化了复杂的布局设计。
基本概念
- 容器 (Container):设置
display: flex 的元素
- 项目 (Item):容器内的直接子元素
- 主轴 (Main Axis):默认水平
- 交叉轴 (Cross Axis):垂直于主轴
容器属性
flex-direction
设置主轴方向。
1 2 3 4
| .container { display: flex; flex-direction: row; }
|
justify-content
主轴对齐。
1 2 3
| .container { justify-content: flex-start; }
|
align-items
交叉轴对齐。
1 2 3
| .container { align-items: stretch; }
|
flex-wrap
换行。
1 2 3
| .container { flex-wrap: nowrap; }
|
align-content
多行交叉轴对齐。
1 2 3
| .container { align-content: stretch; }
|
项目属性
flex-grow
放大比例。
1 2 3
| .item { flex-grow: 0; }
|
flex-shrink
缩小比例。
1 2 3
| .item { flex-shrink: 1; }
|
flex-basis
主轴空间分配前的大小。
1 2 3
| .item { flex-basis: auto; }
|
flex
grow、shrink、basis 的简写。
1 2 3
| .item { flex: 1 1 auto; }
|
align-self
单个项目交叉轴对齐。
1 2 3
| .item { align-self: auto; }
|
实际例子
1 2 3 4 5
| <div class="container"> <div class="item">1</div> <div class="item">2</div> <div class="item">3</div> </div>
|
1 2 3 4 5 6 7 8 9 10 11
| .container { display: flex; justify-content: space-between; align-items: center; height: 100px; }
.item { flex: 1; margin: 0 10px; }
|
浏览器支持
现代浏览器都支持,IE10+ 需要 -ms- 前缀。
总结
Flexbox 让布局变得简单直观。多练习几个例子,你就能掌握它了。