Giao diện tin nhắn chat kiểu messenger: bong bóng chat, avatar, timestamp, màu khác nhau cho sent/received.
Ví dụ
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0 auto;
max-width: 800px;
padding: 0 20px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.message {
font-size: 18px;
font-weight: 500;
border: 2px solid #dedede;
background-color: #55e4a8;
color: rgb(0, 0, 0);
border-radius: 12px;
padding: 12px 16px;
margin: 10px 0;
max-width: 75%;
position: relative;
}
.darker {
border-color: #ccc;
background-color: rgb(111, 25, 182);
color: white;
margin-left: auto;
}
.message::after {
content: "";
clear: both;
display: table;
}
.message img {
float: left;
max-width: 40px;
width: 100%;
margin-right: 12px;
border-radius: 50%;
}
.darker img {
float: right;
margin-left: 12px;
margin-right: 0;
}
.timeStampRight {
float: right;
color: rgba(0,0,0,0.6);
font-size: 12px;
font-weight: bold;
margin-top: 4px;
}
.darker .timeStampRight {
float: left;
color: rgba(255,255,255,0.7);
}
.message-content {
overflow: hidden; /* BFC để text không wrap dưới avatar */
}
</style>
</head>
<body>
<h1>Chat Messages Example</h1>
<div class="message">
<img src="https://i.picsum.photos/id/295/200/200.jpg" alt="User1">
<div class="message-content">
<p>Hello. How are your holidays going?</p>
<span class="timeStampRight">9:00</span>
</div>
</div>
<div class="message darker">
<img src="https://i.picsum.photos/id/255/200/200.jpg" alt="User2">
<div class="message-content">
<p>They are going pretty good. Thanks for asking!</p>
<span class="timeStampRight">9:05</span>
</div>
</div>
<div class="message">
<img src="https://i.picsum.photos/id/295/200/200.jpg" alt="User1">
<div class="message-content">
<p>Are you visiting somewhere in holidays?</p>
<span class="timeStampRight">9:07</span>
</div>
</div>
<div class="message darker">
<img src="https://i.picsum.photos/id/255/200/200.jpg" alt="User2">
<div class="message-content">
<p>Yes! Thinking of going to Disneyland.</p>
<span class="timeStampRight">9:10</span>
</div>
</div>
</body>
</html>
Kết quả
4 bong bóng chat xen kẹ: tin nhắn gửi (màu tím, avatar phải, timestamp trái), tin nhắn nhận (màu xanh mint, avatar trái, timestamp phải).
Cải tiến hiện đại
- Dùng Flexbox thay float cho .message-content
- Thêm mũi tên bong bóng (triangle) với ::before
- Gom nhóm tin nhắn cùng người (chỉ hiện avatar tin nhắn đầu/cuối)