如何为三角形正确添加box shadow?添加后出现正方形阴影问题咨询
哈哈,这个坑我踩过!用border画的三角形直接加box-shadow肯定会变成正方形阴影,原因很简单——box-shadow是跟着元素的盒模型走的,你的:after伪元素本身是宽高都为0的空盒子,那些border只是它的边框,所以阴影会贴合这个空盒子的形状,自然就是正方形了。
下面给你两种可行的解决办法:
解决方案1:用filter: drop-shadow()(推荐)
这种方法最省心,drop-shadow是根据元素的实际可见像素形状生成阴影,而不是盒模型的边框盒,所以能完美贴合气泡和三角形尾巴的轮廓。
修改后的代码如下:
.speech-bubble { display: inline-block; padding: 5px; position: relative; background: #dcf8c6; border-radius: .4em; /* 替换原box-shadow为drop-shadow */ filter: drop-shadow(0px 1px 1px #d0cbc4); } .speech-bubble:after { content: ''; position: absolute; right: 0; top: 50%; width: 0; height: 0; border: 5px solid transparent; border-left-color: #dcf8c6; border-right: 0; margin-top: -5px; margin-right: -5px; /* 删掉这里的box-shadow */ }
<div class="speech-bubble"> Hello Mike! Could you please call me back </div>
解决方案2:用额外伪元素模拟阴影
如果你一定要用box-shadow的逻辑,可以多做一个伪元素来模拟三角形的阴影,把它放在真实尾巴的下层并稍微偏移:
.speech-bubble { display: inline-block; padding: 5px; position: relative; background: #dcf8c6; border-radius: .4em; box-shadow: 0px 1px 1px #d0cbc4; } /* 新增:before伪元素做阴影三角形 */ .speech-bubble:before { content: ''; position: absolute; right: 0; top: 50%; width: 0; height: 0; border: 5px solid transparent; border-left-color: #d0cbc4; /* 用阴影的颜色 */ border-right: 0; margin-top: -5px; margin-right: -6px; /* 比真实尾巴偏右1px,模拟阴影偏移 */ z-index: -1; /* 把阴影放在气泡下层 */ } .speech-bubble:after { content: ''; position: absolute; right: 0; top: 50%; width: 0; height: 0; border: 5px solid transparent; border-left-color: #dcf8c6; border-right: 0; margin-top: -5px; margin-right: -5px; /* 删掉这里的box-shadow */ }
两种方法都能解决问题,第一种更简洁,推荐优先用~
内容的提问来源于stack exchange,提问作者Yerlan Yeszhanov
相关产品推荐
相关产品推荐

