如何用HTML/CSS实现带左上角圆角切角的图片展示效果?
解决左上角切角带圆角的图片展示效果问题

我尝试使用linear-gradient实现如图所示的图片展示效果,但无法为左上角的切角添加border-radius(圆角)。
原尝试代码
CSS
.img-container { background-image: url('https://loremflickr.com/680/520/car,forest'); background-repeat: no-repeat; background-size: cover; border-radius: 0px 42px 42px 4px; position: relative; width: 600px; height: 320px; background-position: 100%; } .img-container::before { content: ''; position: absolute; left: 0; top: -4px; width: 182px; height: calc(100% + 2px); background: linear-gradient(to top left, transparent 50%, white 50.1%) bottom left / 182px no-repeat transparent; }
HTML
<div class="img-container"></div>
问题原因
你用伪元素+linear-gradient的方式,本质是用一个直角三角形的白色遮罩盖住左上角,这种方法没法给遮罩的斜边加圆角——linear-gradient只能生成直线边界的渐变图形,不支持圆角属性。
解决方案1:使用CSS Mask实现
改用CSS mask属性可以同时实现切角和圆角效果,代码如下:
.img-container { background-image: url('https://loremflickr.com/680/520/car,forest'); background-repeat: no-repeat; background-size: cover; border-radius: 0 42px 42px 4px; position: relative; width: 600px; height: 320px; background-position: 100%; /* 核心mask设置 */ mask: /* 左上角切角渐变,预留圆角空间 */ linear-gradient(to top left, transparent 49.5%, white 50%) 0 0 / 182px 100% no-repeat, /* 基础白色遮罩 */ linear-gradient(white, white); mask-composite: exclude; /* 兼容webkit内核浏览器 */ -webkit-mask: linear-gradient(to top left, transparent 49.5%, white 50%) 0 0 / 182px 100% no-repeat, linear-gradient(white, white); -webkit-mask-composite: xor; }
解决方案2:使用Clip-Path Path语法
如果需要更精准的圆角控制,可以用clip-path的path()语法,通过贝塞尔曲线定义带圆角的路径:
.img-container { background-image: url('https://loremflickr.com/680/520/car,forest'); background-repeat: no-repeat; background-size: cover; position: relative; width: 600px; height: 320px; background-position: 100%; /* path中的Q命令定义圆角,数值可按需调整 */ clip-path: path('M 4 0 L 182 0 Q 182 4 178 4 L 600 4 Q 600 46 558 46 L 558 274 Q 558 316 516 316 L 4 316 Q 4 274 4 274 Z'); }
内容的提问来源于stack exchange,提问作者Ravi Gaudani
相关产品推荐
相关产品推荐

