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
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. This works with images of any aspect ratio, and will scale the image to fill the container without stretching/distorting it.
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. This works with images of any aspect ratio, and will scale the image to fill the container without stretching/distorting it.
#avatar {
/* This image is 687 wide by 1024 tall, similar to your aspect ratio */
background-image: url('http://i.stack.imgur.com/Dj7eP.jpg');
/* 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: top center;
/* round the edges to a circle with border radius 1/2 container size */
border-radius: 50%;
}
<div id="avatar"></div>
Another solution is to set the sizes for img and use "object-fit: cover;". It will do the same as the "background-size:cover" without messing with background images.
img {
object-fit: cover;
border-radius:50%;
width: 150px;
height: 150px;
}
<img src="http://i.stack.imgur.com/Dj7eP.jpg" />
I found it on Chris Nager post. - 1
Edit:
As @prograhammer mentioned, this doesn't work on IE. Edge supports it only on <img>
tags.
Partial support in Edge refers to
object-fit
only supporting<img>
- 2
Edit 2: This post of Primož Cigler shows how to use Modernizr to add a fallback support for IE but, in this case, you will need to add a wrapper to de image.
If the image is required to be in the HTML rather than a background image
.wrapper {
width:150px;
height:150px;
margin: 25px auto;
overflow: hidden;
border-radius:50%;
position: relative;
}
.wrapper img {
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%)
}
<div class="wrapper">
<img src="http://lorempixel.com/output/business-q-c-640-480-4.jpg" alt="" />
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With