How to "crop" a rectangular image into a square with CSS?
To remodel your rectangular image into a neat square, ensure width
and height
of the img
element are the same and sprinkle some object-fit: cover
. This neat CSS rule helps your image fill up its space, trimming off the excess, all without deforming the original image.
Voila! You now have a square image. It's all nice and centered, cropped without distorting the aspect ratio.
Advanced techniques and key scenarios
Picture perfect square with a background image
Use a div
to your advantage, sprinkle some background-image
magic for greater control over the image appearance:
This method hits two birds with one stone; it's flexible for div backgrounds plus you can add additional content without tampering with the image display.
Responsive square for the adaptable
Adaptive designs and responsive configurations make your squares comfortable at every screen size:
The container now remains square, striking a pose at any viewport size.
Inclusive design with accessibility
Always remember to include alt
attribute for descriptive information about your image:
Accessibily is king. An alt text can make a world of difference for screen reader users.
Debugging and further boosts
Enhancing centering with flexbox
When it comes to centering and spacing, flexbox is your most reliable ally.
Media queries for adjustable design
Use breakpoints to adapt your page at different canvas sizes:
By adjusting the width
and padding-bottom
within breakpoints, you'll never have to worry about your squares looking odd on different screens.
Square maintenance with pseudo-elements
Use ::after
pseudo-element to create an invisible square and maintain height, without touching the image:
Using ::after
is like having a secret weapon to maintain the aspect ratio without anyone noticing.
Was this article helpful?