让浮动元素高度等于父元素高度

如下图。H为黑色边框即父元素。A,B为子元素,均向左浮动。由于黑色边框设置了overflow:hidden(height属性不设置),B撑大了父元素H,使得H有了高度且为B的高度。

那么问题来了,如何让A的高度等于父元素H的高度?

图片描述

阅读 19.1k
6 个回答

如果用js就很easy了:

$('.A').css('height', $('.B').innerHeight());

当然,纯粹的定位问题一般不建议用js。
应用float的元素设置height:100%;是没用的,但是绝对定位可以。
所以,把.left又包了一层,结构如下:

<div class="container clearfix">
    <div class="right">右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。右侧有很多内容,高度大于left。</div>
    <div class="left-wrapper">
        <div class="left">左侧内容,没有右侧多。左侧内容,没有右侧多。左侧内容,没有右侧多。左侧内容,没有右侧多。</div>
    </div>
</div>
.container{position: relative;overflow: hidden;width: 100%;background-color: rgba(255, 255, 0, 1);}
.right{float:right;width:68%;margin-left:2%;background-color: rgba(0, 0, 255, 0.6);}/* 把元素都设置成了右浮动,因为需要绝对定位的元素在左侧 */
.left-wrapper{float:right;width:30%;}
.left{position:absolute;width:30%;height:100%;background-color: rgba(0, 127, 0, 0.6);}/* 一定要设置left的宽度 */
.clearfix:after{content:".";display:block;clear:both;height:0;overflow:hidden;visibility:hidden;}

可以参考这个问题(Mandarinazul的回答):http://stackoverflow.com/questions/3049783/how-to-make-a-floated-div-100-height-of-its-parent

    
.a{
    margin-bottom: -1000px;
    padding-bottom: 1000px;
}
新手上路,请多包涵

直接设置父元素为dispaly:flex,子元素就会直接继承父元素高度

.root{
    position:relative;
    overflow:hidden;
}
.left{
    position:abusolute;//左侧元素拖出文档流,父容器高度=右,左底部超级长,但是被父元素隐藏;
    padding-bottom:9999rem;
}

这种方法不适用左侧有“可能”比右侧长的情况,也就是说左侧再长,也撑不开父容器;

<style>
    .box{ position: relative; width: 160px; border: 1px solid #000;}
    .box .a{ width: 50px; height: 200px; background: #ccc;}
    .box .b{ left: 60px; top: 0; width: 100px; height: 400px; background: #eee; position: absolute;}
</style>
<div class="box">
    <div class="a">A</div>
    <div class="b">B</div>
</div>
div a ,  div b {
    height: xx; //这里设置a、b两个div的高度相等就可以了
} 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题