Reputation: 725
I am having an image in different size. All having huge size images. I need to show the image without any stretch inside a container. That container had some height. So I have show the image to fit inside the container without any stretch. I need to use image in html not as background image. Here is my code
.image-container {
height: 420px;
width: 100%;
}
@media (max-width: 480px) {
height: 310px;
}
@media (max-width: 375px) {
height: 275px;
}
@media (max-width: 320px) {
height: 240px;
}
.image-container img {
max-height: 100%;
object-fit: contain;
max-width: 100%;
display: block;
margin: 0 auto;
}
<div class="image-container">
<img src="http://media.gettyimages.com/photos/under-the-tree-picture-id480585809" />
</div>
When I use above code image is stretching. Is there any way to fix this? Please suggest any solution for this.
Thanks in Advance.
Upvotes: 0
Views: 4932
Reputation: 4418
Latest solution for this is using object-fit
for IMG
.
Note: Not supported in IE11. Check support here.
Both images are same. Second image has object-fit: cover
.fitImage {
width: 200px;
height: 200px;
object-fit: cover;
}
<img src="https://i.picsum.photos/id/292/200/300.jpg" alt="">
<img src="https://i.picsum.photos/id/292/200/300.jpg" alt="" class="fitImage">
Using jQuery
$(document).ready(function() {
$(".fitImage").each(function(index) {
var imageUrl = $(this).find('img').prop("src");
$(this).css('background-image', "url(" + imageUrl + ")")
});
});
.fitImage {
height: 200px;
width: 200px;
background-size: cover;
background-position: center;
}
.fitImage img {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fitImage">
<img src="https://i.picsum.photos/id/292/200/300.jpg" alt="">
</div>
Upvotes: 0
Reputation: 2642
use max-width
instead of width
in your css to avoid stretching
.img-container img{ max-width:100%; height:auto;}
Upvotes: 0
Reputation: 1641
Always reset the margins and paddings of all elements first.
* {
margin: 0;
padding: 0;
}
If height or width is auto it will not stretch / mutate the original image.
.img-container {
width: 420px; // your width
}
.img-container img {
width: 100%;
height: auto;
display: block;
}
Remove the media queries. Your syntax is incorrect the correct syntax for using them is :
@media (max-width: 480px) {
.img-container {
// some changes in the class props
}
.another-class-change-for-480px-max-width-of-screen {
}
}
Upvotes: 2