两栏布局,左侧固定,右侧自适应的几种方法

两栏布局,左侧固定,右侧自适应
我总结了以下几种方法

  • 左侧固定 + 右侧margin
  • 左侧固定 + 父级padding
  • 左侧浮动 + 右侧BFC
  • 左侧浮动 + 右侧margin
  • 先两个在一行 + 右侧calc
  • 弹性布局

DOM结构

<div class="container">
    <div class="left"></div>
    <div class="right"></div>
</div>

初始样式

<style>
    .container {
        width: 500px;
        height: 300px;
    }

    .left,
    .right {
        height: 100%;
    }

    .left {
        width: 200px;
        background-color: #0ff;
    }

    .right {
        background-color: #f0f;
    }
</style>

两栏布局效果
在这里插入图片描述

第一种

左侧固定 + 右侧margin

<style>
    .container {
        position: relative;
    }
    .left {
        position: absolute;
        left : 0;
        top : 0;
    }
    .right {
        margin-left: 200px;
    }
</style>

第二种

左侧固定 + 父级padding

<style>
    .container {
        position: relative;
        padding-left: 200px;
        box-sizing: border-box;
    }
    .left {
        position: absolute;
        left : 0;
        top : 0;
    }
</style>

第三种

左侧浮动 + 右侧BFC

<style>
    .left {
        float: left;
    }
    .right {
        overflow: auto;
    }
</style>

第四种

左侧浮动 + 右侧margin

<style>
    .left {
        float: left;
    }
    .right {
        margin-left: 200px;
    }
</style>

第五种

先两个在一行(浮动或通过设置display也行,也可以flex) + 右侧calc

<style>
    .left,.right {
        display: inline-block;
    }
    .right {
        width: calc(100% - 200px);
    }
</style>


<div class="container">
    <div class="left"></div><div class="right"></div>
    <!-- 需要考虑空白字符 -->
</div>
<style>
    /*如果父元素没有设置高度,需要清除浮动 */
    .left,.right {
        float: left;
    }
    .right {
        width: calc(100% - 200px);
    }
</style>
<style>
    .container {
        display: flex;
    }
    .right {
        width: calc(100% - 200px);
    }
</style>

第六种

<style>
    .container {
        display: flex;
    }
    .right {
        flex: 1; /* flex : 1 1 0 */
    }
</style>

如果有疑问,可以在评论区留言,也欢迎补充。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值