常用的弹性盒子布局场景加演示图flex

50 阅读2分钟

常用的弹性盒子布局场景加演示图flex

以前为了有更好的兼容性, 一直在使用老的语法,flex,今天就来总结学习一下

元素居中

image-20231021135248156

<body>
<div class="box1">
    <div class="box2"></div>
</div>
</body>
<style>
    .box1{
        width: 300px;
        height: 300px;
        border: 2px dashed #dcb63f;
        background-color: #fff2c7;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .box2{
        width: 100px;
        height: 100px;
        background: #dcb63f;
    }
</style>

justify-content 设置主轴(x轴)对齐方式

  • flex-start(默认值):左对齐
  • flex-end:右对齐
  • center: 居中
  • space-between:两端对齐,项目之间的间隔都相等。
  • space-around:每个项目两侧的间隔相等。所以,项目之间的间隔比项目与边框的间隔大一倍。

image-20231021142033214

左边自适应,右边固定

image-20231021142706471

<div class="box1">
    <div class="item1">1</div>
    <div class="item2">2</div>
    <div class="item3">3</div>
</div>
</body>
<style>
    .box1{
        width: 800px;
        height: 60px;
        border: 2px dashed #dcb63f;
        background-color: #fff2c7;
        display: flex;
    }
    .item1{
        margin-right: 20px;
        height: 50px;
        background: #dcb63f;
        flex: 1;
    }
    .item2{
        margin-right: 20px;
        height: 50px;
        background: #dcb63f;
        flex: 1;
    }
    .item3{
        height: 50px;
        background: #dcb63f;
        width: 50px;
    }
</style>

左边固定,右边自适应

image-20231021142828722

.box1{
    width: 800px;
    height: 60px;
    border: 2px dashed #dcb63f;
    background-color: #fff2c7;
    display: flex;
}
.item1{
    margin-right: 20px;
    height: 50px;
    background: #dcb63f;
    width: 50px;

}
.item2{
    margin-right: 20px;
    height: 50px;
    background: #dcb63f;
    flex: 1;
}
.item3{
    height: 50px;
    background: #dcb63f;
    flex: 1;
}

左右固定,中间自适应

image-20231021142931147

.box1{
    width: 800px;
    height: 60px;
    border: 2px dashed #dcb63f;
    background-color: #fff2c7;
    display: flex;
}
.item1{
    margin-right: 20px;
    height: 50px;
    background: #dcb63f;
    flex: 1;

}
.item2{
    margin-right: 20px;
    height: 50px;
    background: #dcb63f;
    width: 50px;

}
.item3{
    height: 50px;
    background: #dcb63f;
    flex: 1;
}

align-items --> 侧轴(Y轴)排列

  • flex-start:侧轴的起点对齐。
  • flex-end:侧轴的终点对齐。
  • center:侧轴的中点对齐。
  • baseline: 项目的第一行文字的基线对齐。
  • stretch(默认值):如果项目未设置高度或设为auto,将占满整个容器的高度。