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



绝对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>

正如 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
});

小提琴

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

但是,即使它们比它们的祖先大,由于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>

最新更新