如何将弧形尾部置于图片后方?z-index设置无效问题
解决气泡弧形尾部位于背景图片后方的问题
问题核心在于:原写法中,气泡的背景是父元素的背景,而::after伪元素属于父元素的子元素,子元素的层级默认高于父元素的背景层,所以设置z-index为0或-1无法让尾部跑到背景后面。
修改后的代码
.bubble { position: relative; height: 150px; width: 255px; margin-right: 5px; border-radius: 25px 25px 0 25px; border: 2px solid #fff; } /* 用伪元素承载背景图,控制层级高于尾部 */ .bubble::before { content: ""; position: absolute; inset: 0; border-radius: inherit; background-image: url(https://ines-valdovinos.de/images/blog-bubble_teaser.jpg); background-size: contain; z-index: 1; } .bubble::after { content: ""; position: absolute; right: 0; bottom: -50px; height: 50px; width: 25px; border-top-right-radius: 25px; box-shadow: 0 -25px 0 0 #fff; z-index: 0; }
<div class="bubble"></div>
原理说明
- 将背景图移到
::before伪元素中,通过inset:0让它完全覆盖父元素,继承父元素的圆角。 - 给
::before设置z-index:1,::after设置z-index:0,让背景图的层级高于尾部伪元素,从而实现尾部在背景后方的效果。
内容的提问来源于stack exchange,提问作者eness
相关产品推荐
相关产品推荐

