flex 弹性布局
弹性布局是一种按行或按列的一维布局方法。元素可以膨胀以填充多余的空间,收缩以适应更小的空间。
主轴与交叉轴
默认情况下:主轴方向从左至右,交叉轴方向从右至左。
flex 容器
要使用 flex 布局需要现在容器上设置display:flex
改变轴方向 flex-direction
- row(默认)
- row-reverse
- colum
- colum-reverse
换行与缩写 flex-wrap
与传统布局不同,flex 布局不易发生元素溢出。容器被填满时会挤压内部元素的容器(容器的内容不会被挤压)以容纳更多元素。
换行时 flex 会均分容器,使换行的元素在均分后的第二行/列显示。
在不指定 flex 容器的宽度的情况下,容器的宽度会根据块元素的特性占满一行/列。
- nowrap
- wrap
- wrap-reverse
direction 和 wrap 的缩写 flex-flow
第一个参数是方向,第二个参数是换行
demo:flex-flow:row wrap
主轴对齐 justify-content
- flex-start
- flex-end
- center
- space-around(均分空间,使每个元素左右的空间相等)
- space-between(两端对齐,元素之间的间距相同)
- space-evenly(均匀分布,每个元素之间的间距相同)
交叉轴对齐
align-content
相对于整体容器的位置
:::warn
align-content 在未设置换行的情况下不生效
:::
- stretch(不写宽/高时自适应拉伸)
- flex-start
- flex-end
- center
- space-around
- space-between
- space-evenly
align-items
相对于产生换行后每行交叉轴的位置
- stretch
- flex-start
- flex-end
- center
- baseline(基线对齐)
flex 子容器
扩展比例 flex-grow
剩余的空间是 flex 容器的大小减去所有 flex 项的大小加起来的大小。如果所有的兄弟项目都有相同的 flex-grow 系数,那么所有的项目将获得相同的剩余空间,否则将根据不同的 flex-grow 系数定义的比例进行分配。
收缩比例 flex-shrink
博客配置迁移,有空补图。
常见行内元素居中对齐方案
基础 html 结构
<div class="box">
<div></div>
</div>
使用 flex 特性
.box {
width: 200px;
height: 200px;
background-color: azure;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
使用表格布局
.box {
width: 200px;
height: 200px;
background-color: aliceblue;
display: table-cell;
vertical-align: middle;
}
使用绝对定位与 translate 定位
.box {
width: 200px;
height: 200px;
background-color: aliceblue;
position: relative;
}
.box div {
height: 100px;
width: 100px;
background-color: lightblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
使用 BFC 块
flex 会自动将容器转换为 BFC 块。
flex 会解决 margin 的遗留的上下不能自适应的问题。
.box {
width: 200px;
height: 200px;
background-color: aliceblue;
display: flex;
}
.box div {
height: 100px;
width: 100px;
background-color: azure;
margin: auto;
}
子项分组布局
<div class="main">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
.main {
height: 200px;
background-color: aliceblue;
display: flex;
align-items: center;
}
.main div {
width: 100px;
height: 100px;
background-color: antiquewhite;
margin-right: 10px;
}
.main div:nth-of-type(1) {
margin-right: auto;
}
margin 的 auto 属性会自动占满对应方向的剩余空间
等高布局
按照 flex 的特性,不指定高度会自动延伸,使用此特性即可轻松完成等高布局。
<div class="main">
<div>
<p>aaaa</p>
<p>aaaa</p>
<p>aaaa</p>
<p>aaaa</p>
<p>aaaa</p>
</div>
<div>
<p>高度</p>
<p>高度</p>
<p>高度</p>
</div>
</div>
.main {
width: 500px;
background-color: aliceblue;
display: flex;
justify-content: space-between;
}
.main div {
width: 100px;
background-color: antiquewhite;
}
多列布局
使用了 flex-grow:1 会占满剩余空间的特性。
<div class="main">
<div></div>
<div></div>
<div></div>
</div>
body {
margin: 0;
}
.main {
height: 100vh;
background-color: aliceblue;
display: flex;
justify-content: space-between;
}
.main div:nth-of-type(1) {
width: 200px;
background-color: antiquewhite;
}
.main div:nth-of-type(2) {
flex-grow: 1;
background-color: aquamarine;
}
.main div:nth-of-type(3) {
width: 100px;
background-color: beige;
}
同样思路可用于粘性页脚