如何设置绝对定位的元素的父级的高度以与子级增长/收缩 [英] how to set height of parent of absolutely positioned element to grow/shrink with child

查看:373
本文介绍了如何设置绝对定位的元素的父级的高度以与子级增长/收缩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这样:

<div id="parent">
    <div id="child"></div>
</div>

样式如下:

#parent {
    width: 100%;
    padding: 10px;
}

#child {
    position: absolute;
    width: auto;
    left: 0px;
    right: 0px;
}

如何设置 #parent #child 中增加和缩小高度。

how can I set #parent to grow and shrink in height with #child.

我知道将孩子设置为绝对定位拉出它的常规流,所以父元素失去看到孩子的高度的能力,但是有什么方法,我可以清除它也许像你会有一个浮动。

I know that setting child to be absolutely positioned pulls it out of the regular flow so the parent element loses the ability to see the child's height, but is there any way I can clear it maybe like you would with a float?

推荐答案

在CSS中,控件总是从上向下流动,因此子级的高度可以由父级控制,但不能反过来。你可以使用下面的jquery来实现你所期望的:

In CSS the control always flows from top down, so the child's height can be controlled by the parent but not the other way round. You could use the following jquery to achieve what you're after though:

var resizeParent = function() {
  var child_height = $('#child').height();
  $('#parent').height(child_height);
};

$(window).resize(function() {
  resizeParent();
});

$document.ready(function() {
  resizeParent();
});

这篇关于如何设置绝对定位的元素的父级的高度以与子级增长/收缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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