1

The following does exactly what I want, but I don't understand why, which annoys me.

I want:

  • the "second" div to take as much space as it can, within the constraints of its parent
  • then divide that space evenly amongst it's 2 child divs
  • scale the imgs so that they fit exactly in their parent div

<!DOCTYPE html>
<html>
  <head>
    <style>
      .root {
        width: 500px;
        height: 500px;
      }
      .flex-container {
        display: flex;
        flex-direction: column;
        background-color: red;
        height: 100%;
        width: 100%;
      }
      .first {
        background-color: blue;
      }
      .second {
        background-color: darkmagenta;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
      }
      .wrap {
        height: 50%;
        width: 100%;
      }
      img {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div class="root">
      <div class="flex-container">
        <div class="first">
          This div should be sized accoring to it's content and wrap if needed
          which it does, nice!
        </div>
        <div class="second">
          <div class="wrap">
            <img
              src="https://www.publicdomainpictures.net/pictures/30000/velka/cat-13476279941Ls.jpg"
            />
          </div>
          <div class="wrap">
            <img
              src="https://www.publicdomainpictures.net/pictures/30000/velka/cat-13476279941Ls.jpg"
            />
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

After experimenting and messing around I arrived at this HTML and CSS. Crucial is the overflow: hidden; on the "second" div. Without it, the child imgs are displayed larger, growing the "second" div beyond its parent.

I do not understand how overflow: hidden; can affect the size of the childs - I would have expected them to be clipped. Any pointers?

Otto
  • 1,787
  • 1
  • 17
  • 25

1 Answers1

0

I found a nicer way to do this in this post: flex child is growing out of parent

Instead of putting overflow: hidden; on the parent, that posts suggest setting min-height: 0; which allows its children to shrink and become smaller than their content.

That makes more sense to me.

EDIT Found this post with even more detail, and a link to the flexbox spec which explains it all: Why don't flex items shrink past content size?

On a flex item whose overflow is visible in the main axis, when specified on the flex item’s main-axis min-size property, specifies an automatic minimum size. It otherwise computes to 0.

Otto
  • 1,787
  • 1
  • 17
  • 25