flex布局
主成部分
-
弹性容器:父元素
-
弹性盒子:子元素
-
主轴:默认X轴,可以通过flex-direction改变
-
侧轴 / 交叉轴:默认Y轴,可以改变
设置
语法:display: flex
添加位置:父元素
父元素添加 display: flex,子元素可以自动的挤压或拉伸
主轴对齐方式
属性:justify-content
作用:设置弹性盒子(子元素)在主轴上的对齐方式
添加位置:父元素
值:
属性值 | 作用 |
---|---|
flex-start | 默认值, 起点开始依次排列 |
flex-end | 终点开始依次排列 |
center |
沿主轴居中排列 |
space-around |
弹性盒子沿主轴均匀排列, 空白间距均分在弹性盒子两侧 |
space-between |
弹性盒子沿主轴均匀排列, 空白间距均分在相邻盒子之间 |
space-evenly |
弹性盒子沿主轴均匀排列, 弹性盒子与容器之间间距相等 |
侧轴对齐方式
属性:align-items
作用:设置单行子元素在侧轴上的对齐方式
添加位置:父元素
属性:align-self (用在单个子元素上)
作用:设置单个子元素在侧轴上的对齐方式
添加位置:单个子元素
值:
属性值 | 作用 |
---|---|
flex-start | 起点开始依次排列 |
flex-end | 终点开始依次排列 |
center |
沿侧轴居中排列 |
stretch | 默认效果, 子元素如果没有设置具体侧轴方向长度时,弹性盒子沿着侧轴线被拉伸至铺满容器 |
属性:align-content
作用:设置多行子元素侧轴对齐方式
添加位置:父元素
通常与flex-wrap或flex-flow(flow是flex-direction和flex-wrap属性的简写方式)一起用
值:
属性值 | 作用 |
---|---|
stretch | 默认值,弹性盒子没设置侧轴方向长度时,拉伸 |
flex-start | 默认值, 侧轴开始位置对齐 |
flex-end | 侧轴结束位置对齐 |
center | 弹性盒子居中,弹性盒子侧轴方向间离为0 |
space-around | 弹性盒子沿侧轴两端距离是中间等距的一半 |
space-between | 弹性盒子沿侧轴两端位置对齐,中间等距 |
space-evenly | 在沿侧轴方向,弹性盒子两侧等距 |
伸缩比
属性:flex
作用:设置子元素伸缩比
添加位置:子元素
使用:flex:份数
1份 =主轴剩余宽度(如果有间隔,需要去掉所有间隔) /总份数
- 1
- 2
- 3
- 4
- 5
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
ul {
display: flex;
height: 500px;
background-color: #ccc;
}
ul li {
margin-left: 10px;
}
li:nth-child(1){
/* flex:份数 1份 =主轴剩余宽度(如果有间隔,需要去掉所有间隔) /总份数
添加到子元素上 设置子元素伸缩比
*/
flex: 2;
background-color: #f00;
}
li:nth-child(2) {
/* 如果有设置了固定宽度的子元素,1份 =主轴剩余宽度(如果有间隔,需要去掉所有间隔,去掉子元素固定宽度) /总份数 */
/* 如果同时设置了flex,width,优先执行flex,这时width就无效 */
/* flex: 1; */
width: 200px;
background-color: yellow;
}
li:nth-child(3) {
flex: 1;
background-color: green;
}
li:nth-child(4) {
flex: 1;
background-color: pink;
}
li:nth-child(5) {
flex: 1;
background-color: purple;
}
弹性盒子如果同时设置了flex:1,width,优先执行flex:1,这时width就无效
设置主轴方向
属性:flex-direction
作用:修改主轴方向,改变子元素排列方向
添加位置:父元素
值:
属性值 | 作用 |
---|---|
row |
行, 水平(默认值) |
column |
*列, 垂直 |
row-reverse | 行, 从右向左 |
column-reverse | 列, 从下向上 |
- 1
- 2
- 3
- 4
- 5
* {
margin: 0;
padding: 0;
}
ul {
display: flex;
/* 设置主轴方向
row 行, 水平(默认值)
column * 列, 垂直
row-reverse 行, 从右向左
column-reverse 列, 从下向上
*/
flex-direction: column-reverse;
/* 主轴对齐方式 */
justify-content: space-between;
/* 单行子元素侧轴对齐方式 */
align-items: center;
width: 500px;
height: 500px;
margin: 0 auto;
background-color: #ccc;
}
li {
list-style: none;
width: 80px;
height: 80px;
background-color: #f00;
}
li:nth-child(even) {
background-color: #0f0;
}
实现效果:
换行
属性:flex-wrap
作用:实现弹性盒子多行排列效果
添加位置:父元素
值:
属性值 | 作用 |
---|---|
nowrap |
不换行,默认 |
wrap | 换行,主轴X:从上往下 主轴Y:从左向右 |
wrap-reverse | 倒序换行:主轴X:从下向上 主轴Y:从右向左, |
注意: wrap-reverse,会影响到align-content: flex-start/ flex-end;