css - 根据 child 的高度扩展父div的高度

标签 css

我知道这里有几个类似的问题得到解答,但我似乎无法解决这个问题。

我有两个父 div - 一个像带有边框和填充的框架,第二个是纯黑色背景,第三个是实际放置透明图像的位置。我需要两个父 div 根据图像的高度扩展它们的高度。

我可以为黑色背景的 div 工作,但我无法让带有边框的父 div 来扩大其大小:

这是 fiddle :http://jsfiddle.net/vpdj4kst/

#builder_container {
  width: 100%;
  /*overflow: auto;*/
  position: relative;
  padding: 8px;
  border: 1px solid #ccc;
  margin-bottom: 15px;
  display: inline-block;
  clear: both;
}
#builder_contents {
  background: #000;
  width: 100%;
  height: 100%;
  position: relative;
  display: block;
}
.builder_img {
  width: 100%;
  height: auto;
  position: absolute;
}
<div id="builder_container">
  <div id="builder_contents">
    <img class="builder_img" src="image.png" />
  </div>
</div>

最佳答案

这是因为您已将图像设置为 position:absolute;,这会将其从流中取出,导致父元素表现得好像它不存在一样。

Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements.

位置 ( https://developer.mozilla.org/en-US/docs/Web/CSS/position )

.builder_img 中删除 position:absolute;,父容器将对其高度使用react。

#builder_container {
  width: 100%;
  /*overflow: auto;*/
  position: relative;
  padding: 8px;
  border: 1px solid #ccc;
  margin-bottom: 15px;
  display: inline-block;
  clear: both;
}
#builder_contents {
  background: #000;
  width: 100%;
  height: 100%;
  position: relative;
  display: block;
}
.builder_img {
  width: 100%;
  height: auto;
}
<div id="builder_container">
  <div id="builder_contents">
    <img class="builder_img" src="http://coolspotters.com/files/photos/1036167/adidas-st-girls-straw-hat-profile.png" />
  </div>
</div>

关于css - 根据 child 的高度扩展父div的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32224726/

相关文章:

javascript - 你如何让一个 div 进入另一个不固定的 div/nav 菜单?

jquery - jquery中的多个淡入淡出动画

html - 对齐图像的顶部和相邻 div 的顶部

javascript - 使用 Bootstrap 和 Flexslider 的网站上的灯箱问题

jquery - Masonry多图像宽度

javascript - 使用 Css 或 Jquery 移动 Div

cross-browser - 我可以在没有浏览器检测的情况下使用关键帧吗?

css - 仅限 SIFR'ing <LI> parent

javascript - Bootstrap 模式根据 Chrome 中的背景高度多次打印同一页面

javascript - JS - 如何删除使用 substr() 函数生成的字符串中间以外的所有空格?