I have a little problem with some of the images on my website. I have a 280x310 div-container, but all of my images are bigger than this container. I'd like to maintain the aspect ratio of the images, and fit them to the full height of the div, cropping any extra parts of the image on the left and right (keeping the image centered). Is this possible in CSS? Thanks for your help.
-
What's stopping you from using background-image in CSS? – Abhinav Gauniyal Jul 28 '14 at 16:42
-
if you want, your image to fit correctly it your div the best option would be to resize the image to fit your div, if you set width or height to the div, image will be some what blurry. – logan Sarav Jul 28 '14 at 16:56
5 Answers
Add this to your css code
.imgfit { width: 250px; height:500px; object-fit: cover}
Object-fit will do the job for you.

- 87
- 1
- 5
-
Unfortunately not supported in IE - https://caniuse.com/object-fit – Rahul Desai Dec 08 '20 at 22:10
Place the image as a background image for the div and use background-size: contain (to see all of the image) or background-size: cover (to scale and crop)
Check out Set size on background image with CSS?
This can be achieved with a little bit of jQuery:
By setting overflow:hidden
to the div containing the image, and height:100%
to the image, it will be resized to fill the height of the div, without distortion. Then we use jQuery to center the image with position:absolute
.
HTML:
<div class="container">
<img src="http://placehold.it/350x150">
</div>
<div class="container2">
<img src="http://placehold.it/350x150" class="imageid">
</div>
<div class="container2">
<img src="http://placehold.it/600x300" class="imageid">
</div>
CSS:
.container {
border:1px solid red;
width: 280px;
height:310px;
}
.container2 {
border:1px solid blue;
width: 280px;
height:310px;
overflow: hidden;
position:relative;
}
.container2 img {
height:100%;
}
.js-fix {
position:absolute;
top:0;
left:50%;
}
jQuery:
$(".imageid").each(function(){
var hWide = ($(this).width())/2; //half the image's width
hWide = '-' + hWide + 'px';
$(this).addClass("js-fix").css({
"margin-left" : hWide,
});
});
(jQuery code borrowed from here)
You can do this using html:
<img src='image.jpg' alt='Image' width='240' height='310'/>
You can view more of this at http://www.w3schools.com/tags/att_img_height.asp
Also, using css you can make a class or ID for the image itself:
img.sized{
height:310px;
width:210px;
}
Then use the class in your img tag:
<img src='image.jpg' class='sized'/>
You can read more about CSS sizing on http://www.w3schools.com/css/css_dimension.asp

- 229
- 1
- 2
- 10