如何设置绝对定位元素的父级高度与子项生长/缩小

jor*_*ens 5 html css

所以我有这个:

<div id="parent">
    <div id="child"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

风格如下:

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

#child {
    position: absolute;
    width: auto;
    left: 0px;
    right: 0px;
}
Run Code Online (Sandbox Code Playgroud)

如何设置#parent高度增长和缩小#child.

我知道将孩子设置为绝对定位将其拉出常规流程,因此父元素失去了查看孩子身高的能力,但有什么方法可以清除它,就像你想要浮动一样?

Dou*_*ish 5

在CSS中,控件总是从上到下流动,因此孩子的身高可以由父母控制,而不是相反.您可以使用以下jquery来实现您所追求的目标:

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

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

$document.ready(function() {
  resizeParent();
});
Run Code Online (Sandbox Code Playgroud)