我有一些尺寸为480像素宽,640像素高的图片。
我想在网页上使用CSS将它们显示为直径为150像素的圆形。但是我想要看到图像的中心。
因此,从原始图像的顶部和底部各取80像素,可以产生我想要看到的图像正方形。然后我想将其变成圆形。
我尝试过的所有方法都会拉伸图像,因为大多数示例都是以正方形图像为起点。
有人能帮忙吗?
您可以将图像设置为元素的背景,将其背景大小设置为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>
img {
object-fit: cover;
object-position: top center;
border-radius:50%;
width: 150px;
height: 150px;
}
<img src="https://istack.dev59.com/Dj7eP.webp" />
<img>
标签。
Edge的部分支持指的是编辑2: Primož Cigler的这篇帖子展示了如何使用Modernizr为IE添加回退支持,但在这种情况下,您需要为图像添加一个包装器。- 这篇帖子object-fit
仅支持<img>
- 2
.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>
border-radius: 50%
,这绝对是更好的方法。 - user229044另一个解决方案是为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" />
background-position
设置为: top center
而不是仅设置为: center
。这样圆圈就会聚焦于人物的头部而不是胸部,因为在大多数个人资料照片中,头部是图像的中心。 - NaN