Given any arbitrary image, I want to crop a square from the center of the image and display it within a given square.
This question is similar to this: CSS Display an Image Resized and Cropped, but I don’t know the size of the image so I can’t use set margins.
One solution is to use a background image centered within an element sized to the cropped dimensions.
Basic example
Example with
imgtagThis version retains the
imgtag so that we do not lose the ability to drag or right-click to save the image. Credit to Parker Bennett for the opacity trick.object-fit/-positionSee supported browsers.
The CSS3 Images specification defines the
object-fitandobject-positionproperties which together allow for greater control over the scale and position of the image content of animgelement. With these, it will be possible to achieve the desired effect: