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

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

问题描述



我想让我的父容器有一个自动高度,但是我的父容器有一个自动高度。我知道这很难,因为子元素是从他们的位置的页面结构中取出。



我已经尝试设置一个高度到我的父div,我的布局是响应,当它缩小到移动,高度保持不变,因为内容变得堆积,所以高度需要增加与其孩子。



不知道这是否有意义,我没有我的实际代码在我atm但ive是一个小提琴试图解释...



http://jsfiddle.net/dPCky/

解决方案

父母当子元素定位为绝对/固定时,div不能使用 height:auto



您需要使用JavaScript

  var largestHeight = 0; 
//循环遍历元素孩子找到&设置最大的高度
$(。container *)。each(function(){
//如果这个元素的高度大于greaterHeight的值
if($(this).height ()> largestHeight){
//将largestHeight设置为此高度
greaterHeight = $(this).height();
}
}

//设置容器高度
$(。container)。height(largestHeight);

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


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.

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.

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/

解决方案

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

You would need to use JavaScript to achieve this.

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

Working example http://jsfiddle.net/blowsie/dPCky/1/

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

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