flex布局属性及常见应用

171 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第3天

flex布局天天在写,记录一下各种属性及项目开发中常见的应用。

使用flex最初的几个概念:

  • 父容器设置display: flex,一定要在需要排列的元素外包一层: image.png

我们要在红框处设置一个div进行布局

  • 水平居中:justify-content: center
  • 垂直居中:align-items: center

父容器属性

父容器可以有的属性:

属性枚举值含义
flex-directionrow / row-reverse / column / column-reverse主轴的方向
justify-contentflex-start / flex-end / center / space-between / space-around / space-evenly主轴的对齐方式
align-itemsstretch / flex-start / flex-end / center / baseline主轴的对齐方式交叉轴的对齐方式(单行)
align-contentstretch / flex-start / flex-end / center / space-between / space-around主轴的对齐方式(多行)
flex-wrapnowrap / wrap / wrap-reverse是否撑满时换行
flex-flowflex-direction // flex-wraprow nowrap

子容器属性

子容器可以有的属性:

属性枚举值含义
flexnone 或 aoto 或 [flex-grow flex-shrink? flex-basis?]none(0,0,auto) auto(1,1,auto)
flex-grownumber子容器的放大比例。默认是0,即使存在空间也不会放大;最常用是值为1时候,写作flex: 1(1,1,0%)
flex-shrinknumber子容器的缩小比例
flex-basislength / auto固定分配了多少。legnth是分配了多少;aoto是原始尺寸
align-selfauto / stretch / flex-start / flex-end / center / baseline自身修改父容器align-items的对齐,auto默认继承父容器
orderinteger定义元素的顺序

常见应用

image.png

双圣杯布局:左右两侧都是用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>

如常见的电商规格选择,或者地址栏等等都用这个 image.png

上例还可以根据order改变位置: image.png


导航栏也是非常常见的应用,等分在子容器设置flex: 1即可实现,这时候再进行width的赋值也是不生效的! image.png

<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;来实现