页面布局左右固定与自适应(两栏布局)

本文介绍了如何使用CSS实现两栏布局,包括通过相对定位和浮动,以及绝对定位的方法,同时讲解了BFC规则在解决布局问题中的应用,如使用`clear:both`或`overflow:hidden`来防止元素浮动影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.相对定位

给左侧div添加浮动,可以使右侧设置一个marging-left使其宽度自适应

<style>
        body,html{margin: 0;padding: 0;}
        .left{
            float:left ;
            background: #0f0;
            width: 200px;
            height: 300px;
        }
        .right{
            height: 100px;
            margin-left: 200px;
            background: #00f;
        }
        .bottom{
            background: #f00;
        }
    </style>
</head>
<body>
    <div class="all">
        <div class="left">浮动区域</div>
        <div class="right">自适应区域</div>
    </div>
    <div class="bottom">测试布局</div>

 但是我们发现bottom盒子也受到了浮动的影响也在右侧,解决办法就是在bottom样式中添加clear:both;或者添加overflow: hidden;

 2.绝对定位

左侧添加position:absolute

<style>
        body,html{margin: 0;padding: 0;}
        .left{
            position: absolute;
            background: #0f0;
            width: 200px;
            height: 300px;
        }
        .right{
            height: 100px;
            margin-left: 200px;
            background: #00f;
        }
        .bottom{            
            width: 100%;
            /* position: absolute;  */
            /* top: 300px; */
            background: #f00;
            clear:both;
        }
    </style>
</head>
<body>
    <div class="all">
        <div class="left">固定区域</div>
        <div class="right">自适应区域</div>
    </div>
    <div class="bottom">测试布局</div>
</body>

 但是我们发现测试布局位置不对,这是也可以添加一个绝对定位,然后设置top的值即可

.bottom{            
            width: 100%;
            position: absolute; 
            top: 300px;
            background: #f00;
            clear:both;
        }

 如果左侧高度比右侧自适应高,那么测试区域可以不设置绝对定位和高度

        .left{
            position: absolute;
            background: #0f0;
            width: 200px;
            height: 100px;
        }
        .right{
            height: 300px;
            margin-left: 200px;
            background: #00f;
        }
        .bottom{            
            width: 100%;
            /* position: absolute;
            top: 300px; */
            background: #f00;
            /* clear:both; */
        }

 BFC规则

        .left {
        width: 100px;
        height: 150px;
        float: left;
        background: #f66;
        }
        .right {
            height: 200px;
            background: #fcc;
            /* overflow: hidden; */
        }
        .bottom{            
            width: 100%;
            background: #f00;
        }

正常不设置marging-left会导致left看起来在right内部

 当我们添加overflow: hidden;属性后

 即可实现两栏布局

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值