如何将父div的高度设置为子div的位置:绝对 [英] How to set parent div's height as child div with position: absolute

查看:201
本文介绍了如何将父div的高度设置为子div的位置:绝对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有不带高度的父div,也嵌套了另一个子div,其位置绝对在其中.子div的高度为652p​​x.但是我不能在父div中获得相同的高度.我试着玩得很清楚:两者都溢出.

I have parent div which has no height, there is also nested another child div with position absolute inside it. Child div has 652px of height. But I cannot get the same height in parent div. I tried to play with clear: both, overflow.

这是代码:

HTML

    <div class="content">
      <div class="container">
          some other elements whose height is 652px... 
      </div>
     </div>

CSS

.content {
  position: relative;
}

.container {
  position: absolute;
  width: 100%;
  max-width: 1160px;
  margin: 0 auto;
  padding: 120px 0;
}

内容div的高度为0.容器div的高度为652p​​x.如何使内容div的高度与容器div的高度相同?

Content div's height is 0. Container div's height is 652px. How to make content div's height the same as container div's height?

推荐答案

我认为CSS不可能做到这一点,同时又要确保孩子的绝对位置.

I don't think this is possible with CSS while keeping the children absolutely positioned.

绝对定位的元素已从文档流中完全删除,因此它们的尺寸不能更改其父元素的尺寸.

Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.

如果确实必须在将子代保持为position: absolute的同时实现这种影响,则可以使用JavaScript来做到这一点,方法是找到绝对定位的子代在渲染后的高度,并使用其来设置父代的高度

If you really had to achieve this affect while keeping the children as position: absolute, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.

var content=document.querySelector('.content');
var container=document.querySelector('.container');

content.style.height=container.offsetHeight + 'px';

*{box-sizing:border-box;}

.content {
  width: 100%;
  max-width: 1160px;
  margin: 0 auto;
  /*padding: 120px 0;*//*Padding removed for example*/
   border:5px solid green;
}
.container{
  position: absolute;
  overflow: hidden;
  width: 100%;
  border:2px solid red;
  height:652px;
}

<div class="content">
  <div class="container">
    some other elements whose height is 652px...
  </div>
</div>

这篇关于如何将父div的高度设置为子div的位置:绝对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆