持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第3天
flex布局天天在写,记录一下各种属性及项目开发中常见的应用。
使用flex最初的几个概念:
- 父容器设置display: flex,一定要在需要排列的元素外包一层:
我们要在红框处设置一个div进行布局
- 水平居中:justify-content: center
- 垂直居中:align-items: center
父容器属性
父容器可以有的属性:
| 属性 | 枚举值 | 含义 | |
|---|---|---|---|
| flex-direction | row / row-reverse / column / column-reverse | 主轴的方向 | |
| justify-content | flex-start / flex-end / center / space-between / space-around / space-evenly | 主轴的对齐方式 | |
| align-items | stretch / flex-start / flex-end / center / baseline | 主轴的对齐方式 | 交叉轴的对齐方式(单行) |
| align-content | stretch / flex-start / flex-end / center / space-between / space-around | 主轴的对齐方式(多行) | |
| flex-wrap | nowrap / wrap / wrap-reverse | 是否撑满时换行 | |
| flex-flow | flex-direction // flex-wrap | row nowrap |
子容器属性
子容器可以有的属性:
| 属性 | 枚举值 | 含义 |
|---|---|---|
| flex | none 或 aoto 或 [flex-grow flex-shrink? flex-basis?] | none(0,0,auto) auto(1,1,auto) |
| flex-grow | number | 子容器的放大比例。默认是0,即使存在空间也不会放大;最常用是值为1时候,写作flex: 1(1,1,0%) |
| flex-shrink | number | 子容器的缩小比例 |
| flex-basis | length / auto | 固定分配了多少。legnth是分配了多少;aoto是原始尺寸 |
| align-self | auto / stretch / flex-start / flex-end / center / baseline | 自身修改父容器align-items的对齐,auto默认继承父容器 |
| order | integer | 定义元素的顺序 |
常见应用
双圣杯布局:左右两侧都是用width固定宽度,中间内容部分使用flex: 1来定义可变的宽度(因为不同屏幕尺寸需要适配)
需要注意的是,我们可以用width来固定,也可以用flex-basis来固定,比较常见的使用width。
<style>
.box{
display: flex;
background-color: gray;
margin-bottom: 50px;
}
.left {
width: 100px;
background-color:bisque;
}
.main {
flex: 1;
}
.right {
width: 200px;
background-color: lightblue;
}
</style>
<div class="box">
<div class="left">左边固定</div>
<div class="main">中间自伸缩</div>
<div class="right">右边固定</div>
</div>
如常见的电商规格选择,或者地址栏等等都用这个
上例还可以根据order改变位置:
导航栏也是非常常见的应用,等分在子容器设置flex: 1即可实现,这时候再进行width的赋值也是不生效的!
<style>
.box{
display: flex;
background-color: gray;
margin-bottom: 50px;
}
.item {
flex: 1;
text-align: center;
// width不生效
width: 10000px;
}
</style>
<div class="box">
<div class="item">导航1导航1导航1导航1导航1导航1导航1导航1导航1导航1</div>
<div class="item">导航2</div>
<div class="item">导航3</div>
</div>
结束语
- 有很多关于flex-shrink的计算,但是实际应用确实不多
- 有时候align-self会失效,尝试在父元素加固定高度(100%这种不行)
- 最后说下最初的底部bar,左侧就可以用flex-direction: column;来实现