3

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Raphael_S
  • 152
  • 2
  • 3
  • 13

5 Answers5

5

Add this to your css code

.imgfit { width: 250px; height:500px; object-fit: cover}

Object-fit will do the job for you.

olegnaopmaco
  • 87
  • 1
  • 5
3

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?

Community
  • 1
  • 1
Ofir
  • 1,565
  • 3
  • 23
  • 41
3

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.

(http://jsfiddle.net/kK4ZV/)

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)

Community
  • 1
  • 1
johanpw
  • 647
  • 1
  • 11
  • 30
0
position: fixed; 
x-overflow: hidden;
max-width: 100%
XaxD
  • 1,429
  • 14
  • 27
0

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

cdipaolo
  • 229
  • 1
  • 2
  • 10