从矩形图片中创建圆形头像,保持比例并仅使用图像中心。

43

我有一些尺寸为480像素宽,640像素高的图片。

我想在网页上使用CSS将它们显示为直径为150像素的圆形。但是我想要看到图像的中心。

因此,从原始图像的顶部和底部各取80像素,可以产生我想要看到的图像正方形。然后我想将其变成圆形。

我尝试过的所有方法都会拉伸图像,因为大多数示例都是以正方形图像为起点。

有人能帮忙吗?

4个回答

84

您可以将图像设置为元素的背景,将其背景大小设置为cover,然后使用边框半径来圆角边缘。这适用于任何长宽比的图像,并且会缩放图像以填充容器而不拉伸/扭曲它。

#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>


3
background-position 设置为 : top center 而不是仅设置为 : center。这样圆圈就会聚焦于人物的头部而不是胸部,因为在大多数个人资料照片中,头部是图像的中心。 - NaN
1
这实际上是唯一适用于所有图像纵横比的解决方案。 - Ismaeel Sherif

40
另一个解决方案是设置img的大小并使用"object-fit: cover;"。 它将实现与"background-size: cover"相同的效果,而不会干扰背景图像。

img {
  object-fit: cover;
  object-position: top center;
  border-radius:50%;
  width: 150px;
  height: 150px;
}
<img src="https://istack.dev59.com/Dj7eP.webp" />

我在Chris Nager的帖子上找到了它。- 1 编辑: 正如@prograhammer所提到的,这在IE上不起作用。Edge仅支持<img>标签。
Edge的部分支持指的是object-fit仅支持<img> - 2
编辑2: Primož Cigler的这篇帖子展示了如何使用Modernizr为IE添加回退支持,但在这种情况下,您需要为图像添加一个包装器。- 这篇帖子

1
@prograhammer Edge 中的部分支持是指 object-fit 仅在 Edge 上支持 <img>。引自 Can I Use - Brosig
2
结束2020年,Can I Use显示所有当前浏览器都支持此功能。不过IE 11除外。 - Merovex
1
我更喜欢这个解决方案,因为使用背景图像方法不够语义化。然而,在这个答案中,缺少以下行以获得与被接受的答案相同的结果:object-position: top center; - Ola Karlsson
1
Brosig,好方案!@OlaKarlsson:有用的观察!我已经编辑了你的建议。谢谢你们两位。 - undefined

23
如果需要在HTML中使用图像而不是背景图像。

.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="https://via.placeholder.com/640x480" alt="" />
</div>


1
借用 border-radius: 50%,这绝对是更好的方法。 - user229044

2

另一个解决方案是为img元素使用简单的css类:

.avatar {

    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;

    -webkit-box-shadow: 0 0 0 3px #fff, 0 0 0 4px #999, 0 2px 5px 4px rgba(0,0,0,.2);
    -moz-box-shadow: 0 0 0 3px #fff, 0 0 0 4px #999, 0 2px 5px 4px rgba(0,0,0,.2);
    box-shadow: 0 0 0 3px #fff, 0 0 0 4px #999, 0 2px 5px 4px rgba(0,0,0,.2);
}

使用方法:

<img class="avatar" src="http://path.to/image.jpg" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接