我实际上想知道是否可以使用单个伪元素(即图像本身)将图像蒙版为圆形?假设它是一个矩形图像(不是正方形),您希望将其蒙版为圆形,而不挤压图像?
所以你会:
HTML
<img src="#" class="mask">
CSS
.mask {
A lot of CSS possibilities, up to you
}
我知道,使用父 div 并使用 overflow:hidden
& border-radius:50%
是可能的,但是你能不使用第二个吗?伪元素?
更新!
我注意到许多用户似乎认为我只是在寻找 CSS 代码 border-radius:50%
来创建圆形,但事实并非如此。图像应该变成圆形,而不是椭圆形。您可以简单地使用彼此相等的 width
和 height
,但随后图像会被压缩。 答案应包含未压缩的图像结果
解决方案的要求
- 图像应该是一个完美的圆,而不是椭圆
- 图像不应被压缩,无论原始宽高比如何。 即使您使用全景图片,您也只会看到中间部分为圆形,其余部分被隐藏。
最佳答案
如果您只能使用 img 标签在其自身上生成 mask ,那么我能想到的唯一解决方法是: DEMO
.mask {
width: 0px;
height: 0px;
border-radius: 100%;
background:url(http://placehold.it/300x400) center;/* define position to choose clipped area */
padding:50px;/* this makes a 100px square, so a perfect circle can be made with border-radius */
}
如果你可以使用包装器,它可以保留图像使用的原始空间,并且可以通过坐标将蒙版放置在它上面的任何位置。 <强> DEMO
标记:
<div class="mask r150 top100 left150">
<img src="http://placehold.it/300x400" />
</div>
CSS:
.mask {
position:relative;
overflow:hidden;
display:inline-block;/* preserve display behavior of initila image to mask*/
box-shadow:0 0 0 1px;/* show where i stands */
}
.mask img {
display:block;/* a way to remove bottom gap*/
}
.mask:before {
content:'';
position:absolute;
border-radius:100%;
box-shadow:0 0 0 2000px white;
}
.r150:before {
height:150px;
width:150px;
}
.top100:before {
top:100px;
}
.left150:before {
left:150px;
}
使用额外的类可以帮助您调整不同的大小和 mask 位置。
关于image - 仅使用图像本身和纯 CSS 对图像进行圆形 mask ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23545724/