Thomas Thomas - 18 days ago 10
Less Question

Child div height determines parent height?

I have a parent div that contains two children, side by side. The first child is an image that must be height 100% and 58% width, margin auto and overflow hidden. The second child contains text, and the length of the text determines the height of the parent. This is a template for several pages, with different length of text, and therefore different parent height. Is it possible to do what I'm trying to do without using JS? Thanks for your input! Code below.

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;
}

Answer

The problem is your #product-details is floated, which creates a new BFM (block formatting context), and the parent gets collapsed.

I suggest you read more about BFMs here: http://yuiblog.com/blog/2010/05/19/css-101-block-formatting-contexts/

There are several ways to fix this:

  • You could clear the parent, a way to do that is by adding overflow: hidden; to the #product-summary element.
  • You could remove the float: right from #product-details, and use flexbox to align it instead.
Comments