darkchampionz
darkchampionz

Reputation: 1234

Image fit flexbox of certain dimensions

So, I made a similar question a while ago of how an img can fit a div and the answer was to set height: 100% and width: 100% of the image and it worked good. But now I also use a flexbox inside that div and the img still overflows at bottom...

.d1 {
  background: green;
  width: 300px;
  height: 100px;
  padding: 5px;
}

.d2 {
  background: red;
  display: flex;
  padding: 5px;
}

.img1 {
  width: 100%;
  height: 100%;
}
<div class="d1">
  <div class="d2">
    <img class="img1" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Cityoflondon2019june.jpg">
  </div>
</div>

Upvotes: 0

Views: 65

Answers (3)

Sumit Ridhal
Sumit Ridhal

Reputation: 1419

Move height and width from .d1 to .d2.

.d2 {
    width: 300px;
    height: 100px;
}

Upvotes: 0

M Adeel Ahsan
M Adeel Ahsan

Reputation: 213

Basically you will need to add height to img container and object-fit:cover property to img also remove the height from img. PS: object fit will keep the aspect ratio of the image.

<!DOCTYPE html>
<html>
<head>
<style>
.d1 {
    background: green;
    width: 300px;
    height: 100px;
    padding: 5px;
}
.d2 {
    background: red;
    display: flex;
    padding: 5px;
    height: calc(100% - 10px); // minus padding
}
.img1 {
    width: 100%;
    object-fit: cover; //not supported in IE
}
</style>
</head>
<body>

<div class="d1">
    <div class="d2">
        <img class="img1" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Cityoflondon2019june.jpg">
    </div>
</div>

</body>
</html>

codepen link https://codepen.io/madeelahsan/pen/xxxVpbm

Upvotes: 1

Manish
Manish

Reputation: 5066

Give height:100% to the parent div of your image. Also adjust your padding or use calc for setting height height:calc(100% - 10px) See below.

.d1 {
  background: green;
  width: 300px;
  height: 100px;
  padding: 5px;
}

.d2 {
  background: red;
  display: flex;
  padding: 5px;
  height: calc(100% - 10px);
}

.img1 {
  width: 100%;
  height: 100%;
}
<div class="d1">
  <div class="d2">
    <img class="img1" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Cityoflondon2019june.jpg">
  </div>
</div>

Hope this helps :)

Upvotes: 1

Related Questions