CSS-左侧定宽右侧自适应两栏布局

loading 2023年01月04日 67次浏览

比较经典的css练习题,首先上html布局:

<body>
    <div id="box">
        <div id="left"></div>
        <div id="right"></div>
    </div>
</body>

1. flex

通过给父元素设置flex,然后子元素右盒子设置flex:1自适应填满右边区域:

<style>
    #box {
        width: 100%;
        height: 400px;
        display: flex;
    }

    #left {
        width: 100px;
        height: 100%;
        background-color: lightgreen;
    }

    #right {
        flex: 1;
        background-color: lightblue;
    }
</style>

2. 左侧浮动 右侧宽度100%

通过设置左侧浮动,右侧宽度100%来占据左侧普通流的位置:

<style>
    #box {
        width: 100%;
        height: 400px;        
    }

    #left {
        width: 100px;
        height: 100%;
        float: left;
        background-color: lightgreen;
    }

    #right {
        width: 100%;
        height: 100%;
        background-color: lightblue;
    }
</style>

3. 左侧浮动 右侧calc+margin-left

还是设置左侧浮动,不过右侧的宽度通过calc(100%-100px)得出,然后通过margin-left向右移动100px 其实和方法二差不太多

<style>
    #box {
        width: 100%;
        height: 400px;
    }

    #left {
        width: 100px;
        height: 100%;
        background-color: lightgreen;
        float: left;
    }

    #right {
        width: calc(100% - 100px);
        margin-left: 100px;
        height: 100%;
        background-color: lightblue;
    }
</style>

4. 左侧绝对定位 右侧宽度100%

其实和浮动一个原理,都是让左侧脱离文档流然后让右侧盒子占满100% 注意子绝父相即可

<style>
    #box {
        width: 100%;
        height: 400px;
        position: relative;
    }

    #left {
        width: 100px;
        height: 100%;
        background-color: lightgreen;
        position: absolute;
        top: 0;
        left: 0;
    }

    #right {
        width: 100%;
        height: 100%;
        background-color: lightblue;
    }
</style>

5. 左侧绝对定位 右侧calc+margin-left

类似3 不多解释了

<style>
    #box {
        width: 100%;
        height: 400px;
        position: relative;
    }

    #left {
        width: 100px;
        height: 100%;
        background-color: lightgreen;
        position: absolute;
        top: 0;
        left: 0;
    }

    #right {
        width: calc(100% - 100px);
        margin-left: 100px;
        height: 100%;
        background-color: lightblue;
    }
</style>

6. 左右侧均左浮动 右侧calc

其实就是右侧把3中的margin-left换成float:left,这里换成float:right也是一样的

<style>
    #box {
        width: 100%;
        height: 400px;
    }

    #left {
        width: 100px;
        height: 100%;
        background-color: lightgreen;
        float: left;
    }

    #right {
        width: calc(100% - 100px);
        height: 100%;
        float: left;
        background-color: lightblue;
    }
</style>