Cody M. Cody M. - 5 months ago 8
HTML Question

Flexbox child does not respect the boundaries of its parent

I am trying to use flexbox to make a responsive layout. Quite simply, I am trying to have the image in the center of this example perform like this example when the browser windows height and width are manipulated.

The two examples are pretty much the same except that on the first one, a blue banner has been added that has a set height. The green banner needs take up the remaining vertical space and the image needs to respect the height of the green banner.

*note: the blue banners height is dynamic in a sense that I will not know what the height is until the page is rendered. It is hard coded in the example at 200px so the example will work.

Any help would be greatly appreciated.

Code example:

<html>
<body>
<div class="wrapper">
<div class="imageWrapper">
<img src="http://fpoimg.com/1000x800">
</div>
</div>
<div class="stacksWrapper"></div>
</body>
</html>

* { -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; }
html {
margin:0;
padding:0;
height:100%;
width: 100%;
}
body {
margin:0;
padding:0;
background:red;
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
}
.wrapper {
width: 100%;
text-align: center;
background: green;
flex: 1;
flex-basis: 0;
min-height: 0;
position: relative;
}

.imageWrapper {
height:100%;
width: 100%;

img {
max-height:100%;
max-width:100%;
width: auto;
}
}

.stacksWrapper {
height: 200px;
width: 100%;
background-color: blue;
}

Answer

you can also use flex for image wrapper and you may set image in absolute position to avoid see it shrinking :

.imageWrapper {
  height: 100%;  
  width: 100%;
  display:flex;

  img {
      max-height:100%; 
      max-width:100%; 
    /* cure shrinking effect */
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0; 
    /* end cure shrinking effect */
      margin:auto;
  }
}

http://codepen.io/gc-nomade/pen/wWKGOK

Comments