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:
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://img1.jurko.net/wall/paper/donald_duck_4.jpg">
That gives me this:
<img style="width: 200px; height: 150px;" src="http://img1.jurko.net/wall/paper/donald_duck_4.jpg">
And with background-image
I can cut the image 200x100
pixels.
<div
style="background-image:
url('http://img1.jurko.net/wall/paper/donald_duck_4.jpg');
width:200px;
height:100px;
background-position:center;"> </div>
Gives me:
<div style="background-image:url('http://img1.jurko.net/wall/paper/donald_duck_4.jpg'); width:200px; height:100px; background-position:center;"> </div>
How can I do both?
Resize the image and then cut it the size I want?
With CSS3 it's possible to change the size of a
background-image
withbackground-size
, fulfilling both goals at once.There are a bunch of examples on css3.info.
Implemented based on your example, using donald_duck_4.jpg. In this case,
background-size: cover;
is just what you want - it fits thebackground-image
to cover the entire area of the containing<div>
and clips the excess (depending on the ratio).css3 background-image background-size
The containing div with essentially crop the image by hiding the overflow.
You could use a combination of both methods eg.
CSS:
You can use negative
margin
to move the image around within the<div/>
.Did you try to use this?
.centered-and-cropped { object-fit: cover }
I needed to resize image, center (both vertically and horizontally) and than crop it.
I was happy to find, that it could be done in a single css-line. Check the example here: http://codepen.io/chrisnager/pen/azWWgr/?editors=110
Here is the
CSS
andHTML
code from that example:CSS:
HTML: