Hans
Hans

Reputation: 1544

Image not taking parent height

I have following html:

<div class='fullHeight'>
  <div class='flexbox'>
    <div class='first'>
      <p>foo</p>
    </div>
    <div class='second'>
      <p>bar</p>
      <img src='http://www.mandysam.com/img/random.jpg'>
    </div>
  </div>
</div>

and css:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.fullHeight {
  height: 100vh;
  background-color: red;
}
.flexbox {
  display: flex;
  flex-direction: column;
  height: 100%;
  maxHeight: 100%;
  width: 100%;
  background-color: green;
}
.first {
  background-color: magenta;
}
.second {
  background-color: yellow;
  flex: 1 1 auto;
  max-height: 100%;
  height: 100%;
  widht: auto;
}

As long there is no image, everything works fine:

enter image description here

But as soon as a picture comes in, it overflows the container, instead of being shrinked to fit available height:

enter image description here

Codepen

Upvotes: 1

Views: 437

Answers (3)

parisa qomi
parisa qomi

Reputation: 11

Using positions is the other solution but it's very risky and it depends on your plan for future code in this project!!

.second {
  background-color: yellow;
  flex: 1 1 auto;
  max-height: 100%;
  height: 100%;
  widht: auto;
  position:relative
}
.second img{
  height: 95%;
  width: 100%;
  position:absolute;
  bottom:0;
  right:0;
}

Upvotes: 0

Y.T.
Y.T.

Reputation: 2739

You missed

display: flex;
flex-direction: column;

in your .second class, that's why the flex property isn't doing anything. Also it should be max-height instead of maxHeight and width instead of widht.

You can use background-image for your purpose.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.fullHeight {
  height: 100vh;
  background-color: red;
}
.flexbox {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: green;
}
.first {
  background-color: magenta;
}
.second {
  background-color: yellow;
  display: flex;
  flex-grow: 1;
  flex-direction: column;
 }
.container {
  background-color: green;
  flex-grow: 1;
  background-image: url('http://www.mandysam.com/img/random.jpg');
  background-size: contain;
  background-repeat: no-repeat;
}
<div class='fullHeight'>
  <div class='flexbox'>
    <div class='first'>
      <p>foo</p>
    </div>
    <div class='second'>
      <p>bar</p>
      <div class="container">
      </div>
    </div>
  </div>
</div>

Upvotes: 1

Rayco
Rayco

Reputation: 117

Add height and width properties to your image. Or just height. Maybe also object-fit: cover;

.second img {
   height: 100%;
   width: 100%;
   object-fit: cover;
}

Upvotes: 0

Related Questions