css - 用于聊天消息的 div 定位
问题描述
我想以这样的方式创建聊天组件,如果我显示它的所有元素,它将如下所示:
如果我删除了大部分元素,消息将以这种方式显示:
但是我的代码有4个问题:
- 图片和气泡元素不相邻
- 对话泡泡不会因为文字越少而变短;
- 气泡中的文本不在其父 div 上垂直居中,而是在上父容器上;
- 白天元素固定在右侧,而不是与语音气泡的右侧对齐。
我尝试了很多选项,但是我接触 CSS 的次数越多,我创建的问题就越多。
关于如何达到预期结果的任何建议?
这是我的代码:
.container {
position: relative;
margin-left: 5%;
max-width: 90%;
height: auto;
}
.upper-text {
width: 100%;
color: black;
font-size: 12px;
line-height: 120%;
}
.message-container {
width: auto;
}
.character-picture {
width: 30px;
height: 30px;
background-color: aqua;
display: inline-block;
}
.buble-wrapper {
max-width: 75%;
height: auto;
}
.speech-bubble {
background-color: #f0f0f0;
border-radius: 0 20px 20px 20px;
width: auto;
min-height: 40px;
}
.message {
color: black;
font-size: 16px;
padding-left: 4%;
padding-right: 4%;
top: 50%;
transform: translateY(-50%);
}
.lower-tex {
color: black;
font-size: 12px;
line-height: 120%;
text-align: right;
}
<div class="container">
<div class="upper-text">Name</div>
<div class="message-container">
<div class="character-picture"></div>
<div class="buble-wrapper">
<div class="speech-bubble">
<div class="message">text message</div>
</div>
</div>
</div>
<div class="lower-tex">Monday: 20:38</div>
</div>
解决方案
这应该可以满足您的需求。有很大的改进空间,但这会让你开始。
我已经删除了一些我认为不必要的 html,并更改了一些元素的大小和放置方式。
我建议你看看 CSS Flexbox 和 Grid,它们让你可以轻而易举地完成这样的复杂布局。
.container {
width: auto;
max-width: 250px;
display: inline-flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
}
.upper-text {
color: black;
font-size: 12px;
align-self: flex-start;
line-height: 1.5;
}
.message-container {
display: flex;
justify-content: flex-start;
align-items: flex-start;
}
.character-picture {
width: 30px;
height: 30px;
background-color: aqua;
margin-right: 10px;
border-radius: 15px;
flex-shrink: 0;
}
.message {
color: black;
font-size: 16px;
word-wrap: break-word;
padding: 5px 10px;
border-radius: 15px;
background-color: #ccc;
display: flex;
align-items: center;
}
.lower-tex {
color: black;
font-size: 12px;
align-self: flex-end;
line-height: 2.5;
}
<div class="container">
<div class="upper-text">Name</div>
<div class="message-container">
<div class="character-picture"></div>
<div class="message">text message example wow this text wraps very well</div>
</div>
<div class="lower-tex">Monday: 20:38</div>
</div>
推荐阅读
- ios - Sign in with Apple 的本地化标题
- c# - 在 c# 中打印水晶报告时打印机错误“等待加载纸张”
- java - 如何将 ListenableFuture 回调与运行另一个 ListenableFuture 联系起来?
- c# - 截屏的替代方法
- java - 如何更改弹出窗口 TextView 中的文本?
- django - 在 Django 中创建具有数据可视化的新闻网站
- c - Cs50 Speller 未初始化值是由堆分配错误创建的
- ios - JetBrains AppCode - IDE 正在索引用户目录
- function - 第一个用于验证用户输入的 Powershell 函数和正则表达式
- mongodb - Rust Mongo - Mongo 示例代码似乎不起作用