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 imag
There are services like Filestack that will do this for you.
They take your image url and allow you to resize it using url parameters. It is pretty easy.
Your image would look like this after resizing to 200x100 but keeping the aspect ratio
The whole url looks like this
https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.stack.imgur.com/wPh0S.jpg
but the important part is just
resize=width:200/crop=d:[0,25,200,100]
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/>
.
object-fit
may help you, if you're playing with<img>
tag
The below code will crop your image for you. You can play around with object-fit
img {
object-fit: cover;
width: 300px;
height: 337px;
}
You can use Kodem's Image Resize Service. You can resize any image with just a http call. Can be used casually in the browser or used in your production app.
Thanks sanchothefat.
I have an improvement to your answer. As crop is very tailored for every image, this definitions should be at the HTML instead of CSS.
<div style="overflow:hidden;">
<img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>
Try using the clip-path
property:
The clip-path property lets you clip an element to a basic shape or to an SVG source.
Note: The clip-path property will replace the deprecated clip property.
img {
width: 150px;
clip-path: inset(30px 35px);
}
<img src="http://i.stack.imgur.com/wPh0S.jpg">
More examples here.