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

use*_*854 24 html css image avatar

我的图像宽480像素,高640像素.

我希望使用CSS在150px宽的网页上将它们显示为圆圈.但我希望看到图像的中心.

因此,拍摄原始图像的顶部和底部的80px会生成带有我想要看到的图像的正方形.然后我想把它变成一个圆圈.

我尝试的所有内容都会延伸图像,因为大多数示例都是使用方形图像开始.

任何人都可以帮忙

mea*_*gar 56

您可以将图像设置为元素的背景,将其背景大小设置为cover,然后使用border-radius来舍入边缘.

#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%;
}
Run Code Online (Sandbox Code Playgroud)
<div id="avatar"></div>
Run Code Online (Sandbox Code Playgroud)

  • 将 `background-position` 设置为 `: top center` 而不是仅 `: center`。这样,圆圈将聚焦在人的头部而不是胸部,因为在拍摄个人资料照片的大部分时间里,它是图像的中心。 (3认同)

Bro*_*sig 24

另一个解决方案是设置img的大小并使用"object-fit:cover;".它将与"background-size:cover"相同,而不会弄乱背景图像.

img {
  object-fit: cover;
  border-radius:50%;
  width: 150px;
  height: 150px;
}
Run Code Online (Sandbox Code Playgroud)
<img src="http://i.stack.imgur.com/Dj7eP.jpg" />
Run Code Online (Sandbox Code Playgroud)

我在Chris Nager的帖子上找到了它.- 1

编辑:正如@prograhammer所提到的,这对IE不起作用.Edge仅在<img>标签上支持它.

Edge中的部分支持仅指object-fit支持<img>- 2

编辑2: 普里莫兹Cigler的岗位展示了如何使用Modernizr的增加对IE一个后备支持,但是,在这种情况下,你将需要添加一个包装脱图像.

  • 2020 年的总结,Can I Use 显示当前所有浏览器都支持此功能。尽管有 IE 11。 (2认同)

Pau*_*e_D 19

如果图像需要在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%)
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
  <img src="http://lorempixel.com/output/business-q-c-640-480-4.jpg" alt="" />
</div>
Run Code Online (Sandbox Code Playgroud)