CSS3弹性布局(Flexible Box 或 Flexbox)是指通过调整其内元素的宽高,从而在任何显示设备上实现对可用显示空间最佳填充的能力。弹性容器扩展其内元素来填充可用空间,或将其收缩来避免溢出。
块级布局(block)更侧重于垂直方向、行内布局(inline)更侧重于水平方向,与此相对的,弹性盒子布局算法是方向无关的。特别适用于支持那些必须随用户代理(user agent)不同或设备方向从水平转为垂直等各种变化而变换方向、调整大小、拉伸、收缩的应用程序组件。
Flexbox布局中的概念
1.弹性容器
display 的值为flex或者inline-flex就是一个弹性容器
2.弹性项目
弹性容器的子项就是弹性项目
3.轴
弹性布局中有两条轴,弹性项目沿其依次排列的那根轴称为主轴(main axis)。
垂直于主轴的那根轴称为侧轴(cross axis)
用flex-direction来定义主轴
- flex-direction:row 表示横向为主轴,从左到右
- flex-direction:row-reverse 横向为主轴,从右到左
- flex-direction:column 从上到下为主轴
- flex-direction:column-reverse 从下到上为主轴
用justify-content来定义沿主轴怎么排列
用align-items定义弹性项目沿侧轴默认如何排布
用align-self定义单个弹性项目沿侧轴应当如何对齐
4.尺寸:
用flex-grow定义拉伸因子,相当于权重,数字越大占空间越大,负数无效
用flex-shrink定义弹性元素的收缩规则,数字越大收缩的越厉害.负数无效
用flex-basis 指定弹性元素在主轴方向上的初始大小
布局示例
<!DOCTYPE html> <html> <head> <style> #container{ display: flex; flex-direction: row; } .item { background:#f0ad4e; text-align: center; border: 1px solid white; } #container div:nth-of-type(1) {flex-grow:1} #container div:nth-of-type(2) {flex-grow: 4;} #container div:nth-of-type(3) {flex-grow: 1;} </style> </head> <body> <div id="container"> <div class="item">弹性</div> <div class="item">布局</div> <div class="item">示例</div> </div> </body> </html>
<!DOCTYPE html> <html> <head> <style> #container{ display: flex; flex-direction: column-reverse; height: 50vh; } .item { background:#f0ad4e; text-align: center; border: 1px solid white; } #container div:nth-of-type(1) {flex-grow:1} #container div:nth-of-type(2) {flex-shrink: 4;} #container div:nth-of-type(3) {flex-grow: 1;} </style> </head> <body> <div id="container"> <div class="item">弹性</div> <div class="item">布局</div> <div class="item">示例</div> </div> </body> </html>
<!DOCTYPE html> <html> <head> <style> #container{ display: flex; flex-direction: row; justify-content:space-around; } .item { background:#f0ad4e; text-align: center; width: 150px; border: 1px solid white; } </style> </head> <body> <div id="container"> <div class="item">弹性</div> <div class="item">布局</div> <div class="item">示例</div> </div> </body> </html>
<!DOCTYPE html> <html> <head> <style> #container{ display: flex; flex-direction: row; justify-content:center; height: 50vh; background-color: burlywood; } .item { background:#f0ad4e; text-align: center; height:100px; width: 100px; border: 1px solid white; } #container div:nth-of-type(1) {align-self:center} </style> </head> <body> <div id="container"> <div class="item">弹性</div> <div class="item">布局</div> <div class="item">示例</div> </div> </body> </html>