双飞翼布局,圣杯布局实现方式

974 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

双飞翼布局,圣杯布局:两边固定,中间自适应

<div class="box">
     <div class="left"></div>
     <div class="mid"></div>
     <div class="right"></div>
</div>

方案1:父盒子width:100%,相对定位,左右盒子绝对定位,固定宽度,中间盒子不设置宽度,设置margin向内挤

<style>
.box {
    position: relative;
    width: 100%;
    height: 200px;
    border: 1px solid red;
}
.box .left {
    position: absolute;top: 0;left: 0;
    width: 100px;height: 200px;
    background-color: pink;
}
.box .mid {
    margin: 0 100px;
    /*margin规则:盒子没有设置width、height,可以通过设置margin,让盒子向内挤,显示有宽高*/
    height: 200px;
    background-color: skyblue;
}
.box .right {
    position: absolute;top: 0;right: 0;
    width: 100px;height: 200px;
    background-color: pink;
}
</style>

方案2:父盒子使用css3盒子模型box-sizing:border-box,相对定位,给左右内边距,左右盒子绝对定位,宽度固定,中间盒子width:100%

<style>
.box {
    box-sizing: border-box;
    padding: 0 100px;
    position: relative;
    width: 100%;
    height: 200px;
    border: 1px solid red;
}
.box .left {
    position: absolute;top: 0;left: 0;
    width: 100px;
    height: 200px;
    background-color: pink;
}
.box .mid {
    height: 200px;
    width: 100%;
    background-color: skyblue;
}
.box .right {
    position: absolute;top: 0;right: 0;
    width: 100px;
    height: 200px;
    background-color: pink;
}
</style>

方案3:父盒子使用flex布局,左右盒子宽度固定,中间盒子设置flex:1,占满剩余宽度

<style>
.box {
    width: 100%;
    height: 200px;
    border: 1px solid red;
    display: flex;
}
.box .left {
    width: 100px;
    height: 200px;
    background-color: pink;
}
.box .mid {
    flex: 1;    /*设置flex:1;在主轴方向划分剩余空间*/
    height: 200px;
    background-color: skyblue;
}
.box .right {
    width: 100px;
    height: 200px;
    background-color: pink;
}
</style>