I have a square image, and I'd like to put it inside a circle border. How can I make it so that the entire image fits instead of its corners getting cut?
.circle {
width: 200px;
height: 200px;
border: 1px solid black;
border-radius: 100px;
background-image: url('http://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Ski_trail_rating_symbol-blue_square.svg/600px-Ski_trail_rating_symbol-blue_square.svg.png');
background-size: contain;
}
Here it is on jsfiddle.
To render a circle, the image must start out as a square. To work around the problem, we can wrap the img element in a square div element. We then “crop out” the parts of the img element that go beyond the square wrapper div . We can carry this out by setting the wrapper div 's overflow property to hidden .
Now, to turn your square into a circle, set the border-radius property on your element to exactly half of your element's total width or height. My image's size is 256 pixels on each edge and my border has a 10 pixel width. Your once square content is now displays as a circle!
One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.
You need to shrink the image slightly to make it fit within the circle. To calculate the exact size, divide the diameter of the circle by sqrt(2). In this case, 200px / sqrt(2) is about 141px.
Thus, add the following properties:
background-size: 141px;
background-repeat: no-repeat;
background-position: 50%;
JSFiddle
Note that the blue block doesn't touch the circle because the image has a transparent border.
UPDATE: As cassiorenan correctly points out, using a percentage allows the image to automatically scale if you change the size of the circle. Since 1 / sqrt(2) = 0.707..., you can use 70.7% instead of 141px:
background-size: 70.7%;
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