一个高度自适应的div,里面有两个div,一个高度100px,希望另一个填满剩下的高度

html结构如下:

<html>
    <body>
        <div class="content">
            <div class="top"></div>
            <div class="bottom"></div>
        </div>
    </body>
</html>
1.border-box + 负margin方法

实现原理:设置父元素为IE盒模型,且其padding-top为100px, 非绝对定位的子元素“bottom"高度为100%;子元素"top"的margin-top为-100px,导致其会整体上移100px, 也就正好遮挡了父元素的padding-top部分了。
注意点:父元素记得设置box-sizing:border-box

<style>
    html,body{
        height: 100%;
        padding: 0;
        margin: 0;
    }
    .content{
        height: 100%;
        padding: 100px 0 0;
        box-sizing: border-box;
    }
    .top{
        height: 100px;
        margin: -100px 0 0;
        background: greenyellow;
    }
    .bottom{
        height: 100%;
        background: pink;
    }
</style>
2.border-box + 绝对定位方法

实现原理:由于父元素被设置成了IE盒模型,且父元素的padding-top与子元素“top”的高度是一样的, 因此绝对定位的子元素“top”属性设为top:0时,其自然而然就处于父元素的padding-top区域了。(高度相等正好遮盖padding-top,而非绝对定位的子元素bottom的高度设为100%时, 其高度就是父元素盒模型中的content里的高度(不包含padding及margin值),因此正好也就填充了 剩余空间了。
注意点:父元素记得设置position:relativebox-sizing:border-box

<style>
    html,body{
        height: 100%;
        padding: 0;
        margin: 0;
    }
    .content{
        position: relative;
        height: 100%;
        padding: 100px 0 0;
        box-sizing: border-box;
    }
    .top{
        position: absolute;
        height: 100px;
        width: 100%;
        top: 0;
        left: 0;
        background: greenyellow;
    }
    .bottom{
        height: 100%;
        background: pink;
    }
</style>
3.flex方法

实现原理:该方法主要部分就是使用了flex:1属性来实现’子元素’bottom"的自动伸缩
注意点:注意兼容性

<style>
    html,body{
        height: 100%;
        padding: 0;
        margin: 0;
    }
    .content{
        height: 100%;
        display: flex;
        flex-direction: column;
    }
    .top{
        height: 100px;
        background: greenyellow;
    }
    .bottom{
        flex: 1;
        background: pink;
    }
</style>
4.绝对定位方法

实现原理:”bottom“元素采用absolute 绝对定位后,再使用bottom:0属性,会使得其紧贴其包裹的元素的底部。 (准确说是其含有position:relative的父级或以上的包裹元素 )
注意点:父级元素别忘记使用position:relative,否则将定位至html上

<style>
    html,body{
        height: 100%;
        padding: 0;
        margin: 0;
    }
    .content{
        height: 100%;
        position: relative;
    }
    .top{
        height: 100px;
        background: greenyellow;
    }
    .bottom{
        position: absolute;
        top: 100px;
        left: 0;
        right: 0;
        bottom: 0;
        background: pink;
    }
</style>

参考: https://www.jianshu.com/p/050e5cfaa671

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

callmeCassie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值