CSS实现两端固定宽度,中间自适应布局

260 阅读1分钟

HTML代码

    <div class="nav">
        <div class="zhangjinxi">111</div>
        <div class="zhangjinxi2">222</div>
        <div class="zhangjinxi3">33333</div>
    </div>

圣杯布局

.nav {
    background: brown;
    .zhangjinxi {
        height: 200px;
        width: 100%;
        float: left;
        box-sizing: border-box;
        padding: 0 200px;
        background: blue;
    }
    .zhangjinxi2 {
        height: 200px;
        width: 200px;
        float: left;
        margin-left: -100%;
        background: red;
    }
    .zhangjinxi3 {
        height: 200px;
        width: 200px;
        float: left;
        margin-left: -200px;
        background: yellowgreen;
    }
}

双飞翼布局

.nav {
    background: brown;
    position: relative;
    .zhangjinxi {
        height: 200px;
        width: 100%;
        box-sizing: border-box;
        padding: 0 200px;
        background: blue;
    }
    .zhangjinxi2 {
        height: 200px;
        width: 200px;
        position: absolute;
        top: 0;
        background: red;
    }
    .zhangjinxi3 {
        height: 200px;
        width: 200px;
        position: absolute;
        right: 0;
        top: 0;
        background: yellowgreen;
    }
}

flex布局

把中间自适应的部分放在中间,到时就不用再给item设置order属性了,以此按顺序排列就好,用flex最简单,而且没有屏幕缩小时的一些问题

.nav {
    background: brown;
    display: flex;
    height: 200px;
    .zhangjinxi {
        background: blue;
        flex-grow: 1;
    }
    .zhangjinxi2 {
        width: 200px;
        background: red;
    }
    .zhangjinxi3 {
        width: 200px;
        background: yellowgreen;
    }
}

grid布局

和flex一样,最好也是按照顺序摆放,和flex布局一样简单,结果完全一样

.nav {
    background: brown;
    display: grid;
    height: 200px;
    grid-template-columns: 200px 1fr 200px;
    .zhangjinxi {
        background: blue;
    }
    .zhangjinxi2 {
        background: red;
    }
    .zhangjinxi3 {
        background: yellowgreen;
    }
}