css制作聊天框架
使用Flexbox布局创建基础结构
Flexbox适合构建灵活的聊天框架布局。通过设置display: flex和flex-direction: column创建垂直排列的容器,消息区域使用flex-grow: 1占据剩余空间。
.chat-container {
display: flex;
flex-direction: column;
height: 100vh;
max-width: 800px;
margin: 0 auto;
border: 1px solid #ddd;
}
.message-area {
flex-grow: 1;
overflow-y: auto;
padding: 10px;
}
.input-area {
display: flex;
padding: 10px;
border-top: 1px solid #ddd;
}
设计消息气泡样式
消息气泡需要区分发送方和接收方。使用不同的背景色和浮动方向实现视觉区分,配合border-radius创建圆角效果。

.message {
max-width: 70%;
margin-bottom: 12px;
padding: 8px 12px;
border-radius: 18px;
line-height: 1.4;
}
.sent {
align-self: flex-end;
background-color: #0084ff;
color: white;
border-bottom-right-radius: 4px;
}
.received {
align-self: flex-start;
background-color: #f1f0f0;
color: black;
border-bottom-left-radius: 4px;
}
添加时间戳和用户信息
在消息气泡下方添加辅助信息,使用较小的字体和浅色文本。通过::after伪元素或额外HTML元素实现。
.message-meta {
font-size: 0.75rem;
color: #999;
margin-top: 4px;
}
.sent .message-meta {
text-align: right;
}
.received .message-meta {
text-align: left;
}
实现输入框和发送按钮
创建响应式输入区域,确保在不同设备上都能正常使用。按钮使用CSS过渡效果增强交互体验。

.message-input {
flex-grow: 1;
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 20px;
outline: none;
}
.send-button {
margin-left: 10px;
padding: 8px 16px;
background-color: #0084ff;
color: white;
border: none;
border-radius: 20px;
cursor: pointer;
transition: background-color 0.2s;
}
.send-button:hover {
background-color: #0073e6;
}
添加滚动条样式
自定义滚动条提升视觉体验,使用WebKit前缀属性针对不同浏览器进行样式调整。
.message-area::-webkit-scrollbar {
width: 6px;
}
.message-area::-webkit-scrollbar-track {
background: #f1f1f1;
}
.message-area::-webkit-scrollbar-thumb {
background: #ccc;
border-radius: 3px;
}
.message-area::-webkit-scrollbar-thumb:hover {
background: #aaa;
}
响应式设计调整
通过媒体查询确保在小屏幕上也能良好显示,调整布局和字体大小。
@media (max-width: 600px) {
.chat-container {
height: 100vh;
max-width: 100%;
border: none;
}
.message {
max-width: 85%;
}
.message-input {
padding: 6px 10px;
}
}






