I need to always crop a random-sized image to a square 160x160 using only CSS. The images should stay centered when cropped.
My markup should be:
<
With the caveat of it not working in IE and some older mobile browsers, a simple object-fit: cover;
is often the best option.
.cropper {
position: relative;
width: 100px;
height: 100px;
overflow: hidden;
}
.cropper img {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
}
Without the object-fit: cover
support, the image will be stretched oddly to fit the box so, if support for IE is needed, I'd recommend using one of the other answers' approach with -100%
top, left, right and bottom values as a fallback.
http://caniuse.com/#feat=object-fit
<div style="specify your dimension:overflow:hidden">
<div style="margin-top:-50px">
<img ... />
</div>
</div>
The above will crop 50px from the top of the image. You may want to compute to come up wit a top margin that will fit your requirements based on the dimension of the image.
To crop from the bottom simply specify the height of the outer div and remove the inner div. Apply the same principle to crop from the sides.
Try putting your image into a container like so:
HTML:
<div>
<img src="http://www.testimoniesofheavenandhell.com/Animal-Pictures/wp-content/uploads/2013/04/Dog-Animal-Picture-Siberian-Husky-Puppy-HD-Wallpaper.jpg" />
</div>
CSS:
div
{
width: 200px;
height: 200px;
overflow: hidden;
}
div > img
{
width: 300px;
}
Here's a fiddle.
<div>
<img class="crop" src="http://lorempixel.com/500/200"/>
</div>
<img src="http://lorempixel.com/500/200"/>
div {
width: 200px;
height: 200px;
overflow: hidden;
margin: 10px;
position: relative;
}
.crop {
position: absolute;
left: -100%;
right: -100%;
top: -100%;
bottom: -100%;
margin: auto;
height: auto;
width: auto;
}
http://jsfiddle.net/J7a5R/56/
jsFiddle Demo
div {
width: 250px;
height: 250px;
overflow: hidden;
margin: 10px;
position: relative;
}
img {
position: absolute;
left: -1000%;
right: -1000%;
top: -1000%;
bottom: -1000%;
margin: auto;
min-height: 100%;
min-width: 100%;
}
<div>
<img src="https://i.postimg.cc/TwFrQXrP/plus-2.jpg" />
</div>
As Salman A mentioned in the comments, we need to set the img's position coordinates (top, left, bottom, right) to work with percents higher than the image's actual dimensions. I use 1000% in the above example, but of course you can adjust it according to your needs.
* Further explanation: When we set the img's left and right (or: top and bottom) coordinates to be -100% (of the containing div), the overall allowed width (or: height) of the img, can be at most 300% of the containing div's width (or: height), because it's the sum of the div's width (or: height) and the left and right (or: top and bottom) coordinates.
I found a better solutions in following link. Only use "object-fit" https://medium.com/@chrisnager/center-and-crop-images-with-a-single-line-of-css-ad140d5b4a87