Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Display an Image Resized and Cropped

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:

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


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?

like image 825
InfoStatus Avatar asked Jan 29 '09 20:01

InfoStatus


People also ask

How do I show cropped image in CSS?

Using object-fit The object-fit CSS property can be used to easily crop images. It can have five values, but cover is the most suitable. By setting object-fit: cover; , the aspect ratio of the image is preserved while still fitting into the size of its content box.

How can I display just a portion of an image in HTML CSS?

One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want. Just to clarify, you'd set the width and height of the container td, div, span or whatever to 50px to make this work.

How do you scale an image proportionally in CSS?

In that situation we can use CSS max-width or width to fit the image. Use max-width: 100% to limit the size but allow smaller image sizes, use width: 100% to always scale the image to fit the parent container width.


1 Answers

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/>.

like image 137
roborourke Avatar answered Sep 28 '22 04:09

roborourke