如何将父 div 的高度设置为具有位置的子 div:绝对

编程入门 行业动态 更新时间:2024-10-27 04:28:34
本文介绍了如何将父 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:绝对

本文发布于:2023-10-08 04:33:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471521.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   如何将   高度   位置   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!