聊天气泡是即时通讯、客服对话等场景中必不可少的UI组件,通过CSS3的相关属性可以快速实现不同风格的聊天气泡,不需要依赖额外的图片资源,适配性和扩展性都更好。

聊天气泡的实现原理
聊天气泡主要包含两个部分,一个是圆角的矩形气泡主体,另一个是气泡边缘的三角形尖角。矩形主体可以通过border-radius属性实现圆角效果,三角形尖角则可以通过边框的透明特性来绘制,再结合伪元素将尖角定位到气泡主体的边缘位置。
1. 基础三角形绘制
CSS中绘制三角形的核心是利用边框的渲染规则,当一个元素的宽高为0,且四条边框设置不同颜色时,边框的交接处会呈现三角形效果,将不需要的边框设置为透明就能得到单个三角形。下面是绘制向右三角形的代码示例:
/* 向右的三角形 */
.triangle-right {
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 15px solid #e5e5e5;
}
2. 结合伪元素实现气泡尖角
为了避免在HTML中额外添加尖角的标签,我们可以使用::before或者::after伪元素来生成尖角,通过定位属性将尖角贴合到气泡主体的边缘。同时可以给气泡主体添加内边距、背景色、圆角等属性,让气泡看起来更自然。
完整代码示例
左侧聊天气泡(对方发送)
左侧气泡通常是灰色背景,尖角在左侧,代码如下:
/* 气泡容器 */
.chat-left {
position: relative;
max-width: 300px;
padding: 12px 16px;
background-color: #e5e5e5;
border-radius: 8px;
margin: 10px 0 10px 20px;
font-size: 14px;
line-height: 1.5;
}
/* 左侧尖角 */
.chat-left::before {
content: '';
position: absolute;
left: -15px;
top: 15px;
width: 0;
height: 0;
border-top: 8px solid transparent;
border-bottom: 8px solid transparent;
border-right: 15px solid #e5e5e5;
}
<div class="chat-left">
你好,请问这个商品还有库存吗?
</div>
右侧聊天气泡(自己发送)
右侧气泡通常是对主题色背景,文字为白色,尖角在右侧,代码如下:
/* 气泡容器 */
.chat-right {
position: relative;
max-width: 300px;
padding: 12px 16px;
background-color: #07c160;
color: #fff;
border-radius: 8px;
margin: 10px 20px 10px 0;
font-size: 14px;
line-height: 1.5;
margin-left: auto;
}
/* 右侧尖角 */
.chat-right::after {
content: '';
position: absolute;
right: -15px;
top: 15px;
width: 0;
height: 0;
border-top: 8px solid transparent;
border-bottom: 8px solid transparent;
border-left: 15px solid #07c160;
}
<div class="chat-right">
有的,你要多少都可以发货哦。
</div>
带阴影和渐变背景的气泡
如果需要更美观的效果,可以给气泡添加阴影和渐变背景,尖角的颜色需要和背景的渐变色匹配,代码如下:
/* 渐变气泡 */
.chat-gradient {
position: relative;
max-width: 300px;
padding: 12px 16px;
background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
color: #fff;
border-radius: 8px;
margin: 10px 0;
font-size: 14px;
line-height: 1.5;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
/* 渐变气泡尖角,颜色匹配渐变结束色 */
.chat-gradient::before {
content: '';
position: absolute;
left: -15px;
top: 15px;
width: 0;
height: 0;
border-top: 8px solid transparent;
border-bottom: 8px solid transparent;
border-right: 15px solid #2575fc;
}
实现注意事项
- 尖角的尺寸需要根据气泡的圆角和内边距调整,避免出现尖角和气泡主体错位的情况。
- 如果气泡内容包含长文本或者图片,需要设置
max-width限制气泡的最大宽度,避免撑破布局。 - 伪元素的
content属性必须设置,哪怕内容为空,否则伪元素不会渲染。 - 如果需要兼容旧版本浏览器,需要确认
border-radius和伪元素的兼容性,必要时添加前缀。