CSS Display an Image Resized and Cropped

InfoStatus picture InfoStatus · Jan 29, 2009 · Viewed 782.1k times · Source

I want to show an image from an URL with a certain width and height even if it has a different size ratio. So I want to resize (maintaining the ratio) and then cut the image to the size I want.

I can resize with html img property and I can cut with background-image.
How can I do both?

Example:

This image:

enter image description here


Has the size 800x600 pixels and I want to show like an image of 200x100 pixels


With img I can resize the image 200x150px:

<img 
    style="width: 200px; height: 150px;" 
    src="http://i.stack.imgur.com/wPh0S.jpg">


That gives me this:


And with background-image I can cut the image 200x100 pixels.

<div 
    style="background-image:
           url('https://i.stack.imgur.com/wPh0S.jpg'); 
    width:200px; 
    height:100px; 
    background-position:center;">&nbsp;</div>

Gives me:

    <div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;">&nbsp;</div>


How can I do both?
Resize the image and then cut it the size I want?

Answer

roborourke picture roborourke · Jan 29, 2009

You could use a combination of both methods eg.

    .crop {
        width: 200px;
        height: 150px;
        overflow: hidden;
    }

    .crop img {
        width: 400px;
        height: 300px;
        margin: -75px 0 0 -100px;
    }
    <div class="crop">
        <img src="https://i.stack.imgur.com/wPh0S.jpg" alt="Donald Duck">
    </div>

You can use negative margin to move the image around within the <div/>.