2

I'm trying to flex the img and .title elements within a flex-column. When the page is resized the image should grow/shrink while maintaining its aspect ratio and the title text should remain the same height at the bottom of the screen. However, when I reduce the screen height the title text is pushed off the screen.

Also, the height of the .title element may not always be a single line, will not be known prior to rendering.

Code: https://jsfiddle.net/qk4wbfpe/

body {
    
    height: 100vh;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

.container {
    
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
}

.container > img {
    
    flex-grow: 1;
    flex-shrink: 1;
    background-color: blue;
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.container .title {
    
    padding: 10px;
    color: white;
    text-align: center;
    background-color: gray;
}
<div class="container">
    <img src="https://cdn.mos.cms.futurecdn.net/paWPwF85Vkcs8YUuyvA3YM-650-80.jpg.webp">
    <div class="title">
        Planet Earth
    </div>
</div>
Chunky Chunk
  • 16,553
  • 15
  • 84
  • 162

2 Answers2

3

If you add min-height:0 to .container>img it will give the desired result.

body {
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

.container>img {
  flex-grow: 1;
  flex-shrink: 1;
  background-color: blue;
  width: 100%;
  min-height:0;
  object-fit: contain;
}

.container .title {
  padding: 10px;
  color: white;
  text-align: center;
  background-color: gray;
}
<div class="container">
  <img src="https://cdn.mos.cms.futurecdn.net/paWPwF85Vkcs8YUuyvA3YM-650-80.jpg.webp">
  <div class="title">
    Planet Earth
  </div>
</div>
0

add a wrap to your container to make it flow nicely

.container {    
display: flex;

flex-wrap: wrap;

flex-direction: column;
width: 100%;
height: 100%;

and add a flex-basis on your child (img)

.container > img {    
flex-grow: 1;
flex-shrink: 1;

flex-basis: 25%;

background-color: blue;
object-fit: contain;

or you can remove the flex-grow, shrink and shorthand it to

flex: 1 1 25%;

is that what you needed?

Damienov
  • 3
  • 2