Explain Codes LogoExplain Codes Logo

Css Circular Cropping of Rectangle Image

html
responsive-design
css-tricks
web-development
Nikita BarsukovbyNikita Barsukov·Sep 27, 2024
TLDR

To quickly crop a rectangle image into a circle with CSS, apply the border-radius: 50% to a container, use overflow: hidden and leverage flexbox for image centering.

<div class="circle-crop"> <img src="image.jpg" alt="Round Image"/> </div>
.circle-crop { width: 200px; height: 200px; overflow: hidden; display: flex; justify-content: center; align-items: center; position: relative; border-radius: 50%; } .circle-crop img { height: 100%; width: auto; }

This short code ensures any rectangle image is cropped into a circle, keeping aspect ratio and centering the image without distortion.

In-depth walkthrough

Image refinement using object-fit

For better looking circular crops, consider using object-fit: cover. This ensures the image covers the entirety of the container without any stretches or distortions.

.circle-crop img { object-fit: cover; /* Like the perfect fitted suit for your image */ }

This is especially useful when dealing with images of varying sizes and aspect ratios.

Cross-browser support

Dealing with older browsers that do not support object-fit? Here's a trick: apply a background image to the container instead. This ensures consistent behavior across different browsers.

.circle-crop { background: url('image.jpg') no-repeat center center; background-size: cover; /* Background gets a full spa treatment */ }

Always cross-check the browser support for object-fit and clip-path before implementing.

Responsive design considerations

For scaling your circular crops with the viewport, go with percentage values for width and height.

.circle-crop { width: 50%; height: 0; padding-bottom: 50%; /* Stress-free round padding from all sides */ }

Use percentage values for border-radius for smoother scaling with the container size.

Breaking circular crops with clip-path

clip-path can be leveraged for more complex shapes or perfectly clean circular crops:

.circle-crop { clip-path: circle(50%); }

Check the browser support for clip-path prior to implementing it!

Live examples

Remember, to fully understand and apply these CSS tricks, practical coding exercises are key. Creating live examples on platforms like CodePen or JSFiddle can aid understanding:

Dive into code: [CodePen Example](https://codepen.io/yourExample)