Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fit a square HTML image inside a circle border?

Tags:

html

css

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.

like image 537
dee Avatar asked Jul 19 '14 18:07

dee


People also ask

How do I make an image fit a circle in HTML?

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 .

How do I make a square in a circle in HTML?

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!

How do I make an image fit in HTML?

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.


1 Answers

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%;
like image 149
Michael Liu Avatar answered Sep 28 '22 06:09

Michael Liu