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

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

问题描述

我有一个没有高度的父 div,还有另一个子 div,里面有绝对位置.子 div 的高度为 652px.但是我无法在父 div 中获得相同的高度.我试着玩清除:两者,溢出.

代码如下:

HTML

 

<div class="容器">其他一些高度为 652px 的元素...

CSS

.content {位置:相对;}.容器 {位置:绝对;宽度:100%;最大宽度:1160px;边距:0 自动;填充:120px 0;}

Content div 的高度为 0.Container div 的高度为 652px.如何使内容div的高度与容器div的高度相同?

解决方案

我认为在保持孩子绝对定位的同时使用 CSS 是不可能的.

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

如果你真的必须在保持子元素为 position: absolute 的同时实现这种效果,你可以通过 JavaScript 来实现,方法是在渲染后找到绝对定位的子元素的高度,然后使用它设置父级的高度.

var content=document.querySelector('.content');var container=document.querySelector('.container');content.style.height=container.offsetHeight + 'px';

*{box-sizing:border-box;}.内容 {宽度:100%;最大宽度:1160px;边距:0 自动;/*padding: 120px 0;*//例如移除Padding*/边框:5px 纯绿色;}.容器{位置:绝对;溢出:隐藏;宽度:100%;边框:2px 纯红色;高度:652px;}

<div class="容器">其他一些高度为 652px 的元素...

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.

Here is the code:

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;
}

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?

解决方案

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.

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天全站免登陆