如果父绝对div改变高度,调整相对div的大小?

时间:2015-01-04 00:43:17

标签: javascript jquery html css

绝对div获得800的新高度。如何自动调整相对容器的大小?

.relative {
  position: relative;
  width: 600px;
  height: 400px;
  background: #111;
}
.absolute {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 300px;
  height: 200px;
  background: #fff;
}
<div class="relative">  
  
<div class="absolute"> 
</div>
  
</div>

2 个答案:

答案 0 :(得分:0)

定位元素将从文档的正常流中删除,因此更改其大小不会改变其父级的高度。

然而,即使他们比他们的祖先更大,你仍然可以通过overflow看到他们。

在您的情况下,请删除

.st-container {
    overflow: hidden;
}
.st-content {
    overflow-y: hidden;
}

然后,它仍将成为默认的overflow: visible,因此绝对元素仍然可见(溢出),因此您将能够使用页面的滚动条来完全看到它。

document.getElementById('btn').onclick = function() {
  document.getElementById('absolute').style.height
  = document.getElementById('relative').clientHeight*2 + 'px'
};
html,body {
  margin: 0;
  height: 100%;
}
#relative {
  position: relative;
  width: 100%;
  height: 100%;
  background: #111;
}
#absolute {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 300px;
  height: 150px;
  background: #aaf;
}
<div id="relative">  
  <div id="absolute">
    <input id="btn" type="button" value="Change size" />
  </div>
</div>

答案 1 :(得分:0)

正如Oriol所说,你不应该使用position: absolute,因为它会从文档流中删除元素,因此不会注册height。如果您正在查找类似于您发布的行的示例,则可以执行的操作将容器设置为display: none并使用jquery的slideDown(或slideToggle如果您希望容器显示并隐藏):

<强> HTML

<button>Click Me</button>

<div class="info">
   <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

   <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

<强> CSS

.info{
  display: none;
  background: black;
  color: #FFF;
}

<强> JS

$("button").click(function(){
  $(".info").slideDown();
  $(this).hide(); //the example you used hid the button after clicking
});

FIDDLE