CSS Display an Image Resized and Cropped
With CSS3 it's possible to change the size of a background-image
with background-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 the background-image
to cover the entire area of the containing <div>
and clips the excess (depending on the ratio).
.with-bg-size {
background-image: url('https://i.stack.imgur.com/wPh0S.jpg');
width: 200px;
height: 100px;
background-position: center;
/* Make the background image cover the area of the <div>, and clip the excess */
background-size: cover;
}
<div class="with-bg-size">Donald Duck!</div>
css3 background-image background-size
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/>
.