欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

让浮动元素高度等于父元素高度 高度一样 高度一致 等高? 有大用

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


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


 


2 个回答

很简单,不用浮动布局,改用 flexbox。                                    
发布于 2016-03-01                                    

纯CSS的话给A加个padding-bottom:9999px;margin-bottom:-9999px。                                

来自  https://www.zhihu.com/question/40903651?sort=created        


                               

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

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

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

如果用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; }
                               



                               

.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的高度相等就可以了
} 
                               

                        
                               


                                  


普通分类: