user3086854 user3086854 - 1 year ago 159
CSS Question

Create a circle avatar from a rectangle image keeping proportions and just using centre of image

I have images that are 480px wide by 640px high.

I want to display them as circles on a webpage 150px wide using CSS. But I want to see the centre of the image.

So take 80px of the top and bottom of the original image produces the square with the image I want to see. I then want to make that into a circle.

Everything I try stretches the image as most examples are to use a square image to start with.

Can any one help

Answer Source

You can set the image as the background of an element, set its background-size to cover, and then use border-radius to round the edges.

#avatar {
    /* This image is 687 wide by 1024 tall, similar to your aspect ratio */
    background-image: url('');
    /* make a square container */
    width: 150px;
    height: 150px;

    /* fill the container, preserving aspect ratio, and cropping to fit */
    background-size: cover;

    /* center the image vertically and horizontally */
    background-position: center;

    /* round the edges to a circle with border radius 1/2 container size */
    border-radius: 50%;
<div id="avatar"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download