关于父元素设置min-height,子元素设置 height 100% 不生效的问题

<div class="container">
    <div class="child"></div>
</div>

<style>
    .container {
        min-height: 100px;
        border: 1px solid;
    }
    .child {
        height: 50%;
        background: red;
    }
</style>

问题:子元素 height 仍然为 0

解决办法

第一种: 父元素设置position: relative, 子元素设置 position:absolute

<div class="container">
    <div class="child"></div>
</div>

<style>
    .container {
        min-height: 100px;
        border: 1px solid;
        position: relative;
    }
    .child {
        width: 100%;
        height: 50%;
        background: red;
        position: absolute;
    }
</style>

第二种: 给父元素加一层 box, 给 box 添加 flex 布局

<div class="box">
    <div class="container">
        <div class="child"></div>
    </div>
</div>

<style>
    .box {
        display: flex;
    }
    .container {
        width: 100%;
        min-height: 100px;
        border: 1px solid;
    }
    .child {
        height: 50%;
        background: red;
    }
</style>

第三种: 父元素添加 display: grid;  

<div class="container">
   <div class="child"></div>
</div>

<style>
    .container {
        width: 100%;
        display: grid;
        min-height: 100px;
        border: 1px solid;
    }
    .child {
        height: 50%;
        background: red;
    }
</style>

下边的方法不贴代码了

第四种:给子元素添加 min-height inherit,

这个的问题在于,如果父元素的高度比 min-height 高,子元素不会自动变高

第五种:给父元素添加 display: flex; flex-direction: column; 子元素添加 flex: auto;

这个问题在于,没法设置为50%的高度。

第六种: display:table; 

  • 39
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值