Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS circular image at any size

Tags:

html

jquery

css

I am creating a circular image with CSS.

When my image is 200px x 300px, it's not a perfect circle:

.circular {
  margin: auto;
  width: 200px;
  height: 300px;
  border-radius: 150px;
  -webkit-border-radius: 150px;
  -moz-border-radius: 150px;
  background: url(http://i.stack.imgur.com/S1ZCs.jpg) no-repeat;
}
<div class="circular"></div>

Here is a jsFiddle as well.

Is there a way to make a perfect circle when the width and height are different sizes? If I set this to 300 x 300 it's a perfect circle, but I need it to be in a perfect circle when the image is 200 x 300.

like image 460
user979331 Avatar asked Nov 30 '22 01:11

user979331


1 Answers

You can't make it a circle if the values aren't square, its that simple. You can, however, make the wrapper square and hide the remains of the circle if you nest your image in it. It would be something like this:

.circular {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  position: relative;
  overflow: hidden;
}
.circular img {
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
<div class="circular">
  <img src="http://www.placehold.it/150" />
</div>

I usually wrap all the lines between and including position: and transform:in a separate CSS definition with the :nth-child(n)selector so the centering only works on browser that support nth-child, but thats just fine-tuning.

like image 199
somethinghere Avatar answered Dec 04 '22 09:12

somethinghere