Home > Software design >  How to display a rectangular image inside a circle using CSS
How to display a rectangular image inside a circle using CSS

Time:06-13

I am given a rectangular picture of width=300px and height=300px.

I want to show this picture inside a circle and came up with the following CSS:

img {
  width: 300px;
  height: 300px;
  background-color: white;
  border-radius: 50%;
  border: 2px solid black;
}

The issue that I am having is that the picture doesn't really seem to fit nicely inside the circle. It seems way to big and I think that's because the circular form is cropping off parts of the image. So, how could I avoid this? I guess I could simply upload a smaller image. An image of size 200px x 200px, however, would likely be distorted since the circle is too big for it and thus the image would be enlarged.

Any suggestions?

Here is an example of the picture I am adding:

rectangular

And here it is in a circle:

circular

CodePudding user response:

I would do this with a background image, which gives you more control over how it sits in its container (in this case a <div>).

You can set the background size and position to accommodate a non-symmetric image such as yours.

div {
  width: 300px;
  height: 300px;
  background-color: white;
  border-radius: 50%;
  border: 2px solid black;
  background-image: url(https://i.imgur.com/z7YIJI6.png);
  background-size: 80% 80%;
  background-position: 50% 70%;
  background-repeat: no-repeat;
}
<div></div>

Results:

Results

CodePudding user response:

Suggestion using <div> as wrapper:

img {
  z-index: -1;
  width: 300px;
  height: 300px;
  margin: auto;
  display: block;
  margin-top: 45px;
  position: relative;
}

div {
  width: 350px;
  height: 350px;
  display: block;
  border-radius: 50%;
  border: 2px solid black;
}
<div>
  <img src="https://i.stack.imgur.com/oWAqE.png">
</div>

  • Related