Paula
Paula

Reputation: 399

How to use img-fluid, set a custom height and not deform the image?

I have an image that is fluid (.img-fluid) and I've set a height of 245px and it's width is always 100%. When I check my page on small devices, the height works just fine, but the image looks squeezed in it's width. My image must always looks correctly, not squeezed.

enter image description here

<div class="product-image">
    <img src="https://static.reverb-assets.com/assets/homepage/open-graph- 
    7c32c7390769b2d0ab9366d1547b0a829b1c44f2eb991a9b0d1b3f59d0e62bf4.jpg" 
    alt="Foto del producto" class="img-fluid">
</div>
.product-image {
  width: 100%;
  height: 245px;
}

.product-image .img-fluid {
  max-width: 100%;
  height: 100%;
}

Upvotes: 0

Views: 2308

Answers (2)

bron
bron

Reputation: 1548

Use on both sides of the image an auto value

<div class="product-image">
  <img src="https://via.placeholder.com/150x245.png" alt="Foto" class="img-fluid">
</div>

.product-image {
  width: 100%;
  height: 245px;
}
.product-image .img-fluid {
  display: block;
  width: auto;
  max-width: 100%;
  height: auto;
  max-height: 100%;
}

Upvotes: 0

Andrew Vasylchuk
Andrew Vasylchuk

Reputation: 4779

Looks like object-fit CSS property should fit your needs.

Reference.

img {
  width: 100%;
  height: 245px;
}

.img--cover {
  object-fit: cover;
}

.img--contain {
  object-fit: contain;
}
<div>
  <img src="https://www.talentz.net/wp-content/uploads/CG10-2.jpg" alt="Foto del producto" class="img--cover">
</div>
<div>
  <img src="https://www.talentz.net/wp-content/uploads/CG10-2.jpg" alt="Foto del producto" class="img--contain">
</div>

Upvotes: 1

Related Questions