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

问题描述



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



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



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



解决方案

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



 <$ c 

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

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

工作范例


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 examplehttp://jsfiddle.net/blowsie/dPCky/1/

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

08-23 03:46