具有绝对/固定子级的父容器上的自动高度 [英] Auto height on parent container with Absolute/Fixed Children

查看:9
本文介绍了具有绝对/固定子级的父容器上的自动高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为一个包含 2 个子元素的 div 设置一个自动高度,这些子元素的位置是固定的并且绝对是分开的.

Im trying to set an automatic height a div that contains 2 child elements, positioned fixed and absolutely respecitvely.

我希望我的父容器具有自动高度,但我知道这很难,因为子元素与其位置一起从页面结构中取出.

I want my parent container to have an auto height but I know this is hard as the child elements are taken out of the page structure with their positions.

我已经尝试为我的父 div 设置一个有效的高度,但是我的布局是响应式的,当它缩小到移动设备时,高度保持不变,因为里面的内容被堆叠起来,所以高度需要增加它的孩子.

I have tried setting a height to my parent div that works, but with my layout being responsive, when its scaled down to mobile, the height remains the same where as the content within becomes stacked and so the height needs to increase with its children.

不确定这是否有意义,我在 atm 上没有我的实际代码,但我做了一个小提琴试图解释......

Not sure if this makes sense, I dont have my actual code on me atm but ive made a fiddle trying to explain...

http://jsfiddle.net/dPCky/

推荐答案

父 div 不能使用 height:auto 当它的子级被定位为绝对/固定时.

The parent div can not use height:auto when its children are positioned absolute / fixed.

您需要使用 JavaScript 来实现这一点.

You would need to use JavaScript to achieve this.

jQuery 中的示例:

An example in jQuery:

var biggestHeight = 0;
// Loop through elements children to find & set the biggest height
$(".container *").each(function(){
 // If this elements height is bigger than the biggestHeight
 if ($(this).height() > biggestHeight ) {
   // Set the biggestHeight to this Height
   biggestHeight = $(this).height();
 }
});

// Set the container height
$(".container").height(biggestHeight);

工作示例http://jsfiddle.net/blowsie/dPCky/1/

这篇关于具有绝对/固定子级的父容器上的自动高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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