子div高度决定父高?

时间:2016-11-14 21:45:02

标签: html css less

我的父母div包含两个孩子,并排。第一个孩子是一个图像,必须是高度100%和58%宽度,边距自动和溢出隐藏。第二个子项包含文本,文本的长度决定了父项的高度。这是几个页面的模板,具有不同的文本长度,因此父级高度不同。如果不使用JS,我可以做我想做的事吗?感谢您的输入!代码如下。

HTML:

<div id="product-summary">

  <div class="product-image-container">
    <img />
  </div>

  <div id="product-details">
    <h3 class="product-title"></h3>
    <div class="product-description"></div>
  </div>

</div>

CSS:

.product-image-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 58%;
  height: 100%;
  overflow: hidden;

  img {
    position: absolute;
    top: 0;
    left: 50%;
    margin: auto;
    transform: translateX(-50%);
    min-width: 100%;
    height: 100%;
  }
}

#product-details {
  float: right;
  border: solid thin #777;
  height: ~"calc(100% - 2px)";
  width: 41%;
  text-align: center;
}

2 个答案:

答案 0 :(得分:7)

问题是您的#product-details浮动,这会创建一个新的BFM(块格式化上下文),并且父级会崩溃。

我建议您在此处阅读有关BFM的更多信息:http://yuiblog.com/blog/2010/05/19/css-101-block-formatting-contexts/

有几种方法可以解决这个问题:

  • 你可以清除父母,一种方法是通过添加overflow:hidden;到#product-summary元素。
  • 你可以从#product-details中删除浮动:直接使用flexbox来对齐它。

答案 1 :(得分:0)

我不知道任何预处理器的魔法,但使用inline-block效果很好,并且保留positioned absolute个父元素包含在relative父级中以进行控制。没有提到图像的显示方式,所以我假设宽高比不变,没有裁剪。

&#13;
&#13;
.product-image-container {
  display: inline-block;
  position: relative;
  top: 0;
  left: 0;
  right: 0;
  width: 58%;
  height: 100vh;
  overflow: hidden;
}
img {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: auto;
}
#product-details {
  float: right;
  border: 1px solid #777;
  height: 100%;
  width: 41%;
  text-align: center;
}
a {
  margin-left: 50%;
}
&#13;
<div id="product-summary">

  <div class="product-image-container">
    <img src='https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png'>
  </div>

  <div id="product-details">
    <h3 class="product-title">Lena Söderberg</h3>
    <div class="product-description">
      <blockquote>Lenna or Lena is the name given to a standard test image widely used in the field of image processing since 1973. It is a picture of Lena Söderberg, shot by photographer Dwight Hooker, cropped from the centerfold of the November 1972 issue of Playboy
        magazine.
      </blockquote>
      <a href='https://en.wikipedia.org/wiki/Lenna'>Wikipedia</a>
    </div>
  </div>

</div>
&#13;
&#13;
&#13;

相关问题