.box { position: relative; background-color: #ffffff; padding: 20px; border-radius: 8px; box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.1); } .box:before { content: ''; position: absolute; width: 0; height: 0; border-style: solid; border-width: 10px 10px 0 10px; border-color: #ffffff transparent transparent transparent; bottom: -10px; left: 50%; transform: translateX(-50%); }
上述代码是最基本的CSS消息框箭头实现方式。它首先需要一个父元素.box,为其设置样式,其中relative属性非常关键。在该元素中大家使用:before来设置箭头,而且通过动态transform将箭头居中对齐。
.box { position: relative; background-color: #ffffff; padding: 20px; border-radius: 8px; box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.1); } .box:before { content: ''; position: absolute; width: 0; height: 0; border-style: solid; border-width: 10px 10px 0 10px; border-color: #ffffff transparent transparent transparent; bottom: -10px; left: 50%; transform: translateX(-50%) rotate(180deg); }
至于为什么要对transform添加rotate属性?这是因为原本的箭头朝下,而大家需要的是朝上的箭头,只需要将箭头旋转180度即可。
除非你是设置特定的箭头出现在消息框的某个特定区域内,否则上述代码已经可以满足大部分情况的需求。您可以将.box和.box:before的样式调整为符合您的项目需求。