CSS Flex布局
Flex布局是W3C提出的具有强大空间分布和对齐能力的布局方案。到目前为止,得到了所有浏览器的支持。
Flex布局意为弹性布局,用来为盒状模型提供强大的灵活性
其最显著的效果就是把原本上到下排列的块状元素变成水平排列:
![](https://i2.wp.com/fireinsect.top/wp-content/uploads/2022/07/image-3.png?resize=569%2C332&ssl=1)
.container {
display: flex;
background: #D5E8D4;
border: 1px solid #5D9E5A;
}
注意的是:使用Flex布局后,子元素的float、clear和vertical-align属性将失效
此时,我们称父元素为容器,子元素为项目
Flex水平和垂直方向上的分布
Flex容器使用justify-content
和align-items
来分别条件水平和垂直方向上的分布
justify-conten
t有六个有效值:
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
![](https://i0.wp.com/fireinsect.top/wp-content/uploads/2022/07/image-4.png?resize=582%2C552&ssl=1)
align-items有五个有效值:
align-items: flex-start | flex-end | center | baseline | stretch;
![](https://i1.wp.com/fireinsect.top/wp-content/uploads/2022/07/image-5.png?resize=591%2C560&ssl=1)
flex-wrap
Flex容器中,一般情况下,项目都是单行排列,不会换行。当所有项目和宽度超过容器宽度时,项目会在宽度上进行压缩,如果想让项目换行,可以使用flex-wrap
属性,其有三个取值 nowrap | wrap | wrap-reverse
![](https://i0.wp.com/fireinsect.top/wp-content/uploads/2022/07/image-6.png?resize=488%2C719&ssl=1)
flex:none
我们已经知道了,当项目超过容器的宽度,默认情况下,项目宽度会被压缩,但我们希望其不被压缩,且不换行时,可以使用 项目属性 flex:none
使得项目不能被压缩或者放大:
![](https://i0.wp.com/fireinsect.top/wp-content/uploads/2022/07/image-7.png?resize=608%2C515&ssl=1)
flex:1
如果一行有剩余的情况下,我们希望项目能够均匀放大,撑满水平方向,就可以给所有项目加上flex:1
属性:
![](https://i1.wp.com/fireinsect.top/wp-content/uploads/2022/07/image-8.png?resize=617%2C448&ssl=1)
![](https://i2.wp.com/fireinsect.top/wp-content/uploads/2022/07/image-9.png?resize=656%2C593&ssl=1)
使用这个方法,我们可以通过:
<div class="flex-auto">
<div class="static"></div>
<div class="flexible"></div>
</div>
.flex-auto {
display: flex;
}
.flex-auto .static {
width: 100px;
flex: none;
}
.flex-auto .flexible {
flex: 1;
}
实现一栏固定,一栏自适应的效果
![](https://i1.wp.com/fireinsect.top/wp-content/uploads/2022/07/image-10.png?resize=480%2C308&ssl=1)
flex-direction 主轴设定
在flex布局中,有两根轴,主轴和交叉轴:
![](https://i1.wp.com/fireinsect.top/wp-content/uploads/2022/07/image-11.png?resize=800%2C586&ssl=1)
默认情况下:主轴为水平从左到右,交叉轴为垂直,从上到下。容器都是默认按照主轴方向排列的。
我们可以使用flex-direction
来改变主轴、交叉轴方向,其有四个值: row | row-reverse | column | column-reverse
![](https://i0.wp.com/fireinsect.top/wp-content/uploads/2022/07/image-12.png?resize=593%2C188&ssl=1)
主轴的变化会导致justify-content
和align-items
的控制方向变化