css - 如何将新的子元素和滚动条附加到父 div 的底部?
问题描述
我正在制作一个聊天应用程序。用户提交一条消息,它会填入聊天记录的底部。一条新消息将在底部替换它并将其向上推。当消息超过日志的高度时,会出现一个滚动条。默认情况下,新消息仍应出现,即滚动条应锚定在底部,除非另有移动。
我很难做到这一点。直觉上我想做
.chatlog {
display: flex;
flex-direction: column;
justify-content: flex-end;
overflow-y: auto;
}
但显然 flex-end 和 overflow: auto 是不兼容的。我努力了:
.chatlog {
display: flex;
flex-direction: column;
justify-content: flex-start;
overflow-y: auto;
}
.chatlog:first-child {
margin-top: auto;
}
但没有成功。我还尝试在 .chatlog 的底部添加一个 .anchor div
.chatlog {
display: flex;
flex-direction: column;
overflow-y: auto;
overflow-anchor: none;
}
.anchor {
overflow-anchor: auto;
height: 1px;
}
考虑到有多少网站有某种聊天界面,我不觉得这是一个不常见的要求,但我还没有找到任何可行的解决方案。
解决方案
尝试将其包装在容器中:
html {
height: calc(100vh - 16px);
}
body, .container {
height: 100%;
}
.container {
height: 100%;
overflow: auto;
resize: both;
min-width: 250px;
max-width: 100%;
min-height: 150px;
max-height: 100%;
}
.chatlog {
display: flex;
flex-direction: column;
justify-content: flex-end;
overflow-y: auto;
min-height: 100%;
background: lightgrey;
}
.chatlog .msg-container.me {
justify-content: flex-end;
display: flex;
}
.chatlog .msg-container .msg {
border-radius: 5px;
width: fit-content;
margin: 8px;
padding: 8px;
}
.chatlog .msg-container.other .msg {
background: white;
}
.chatlog .msg-container.me .msg {
background: lightgreen;
}
<div class = 'container'>
<div class = 'chatlog'>
<div class = 'msg-container other'>
<div class = 'msg'>Hi</div>
</div>
<div class = 'msg-container me'>
<div class = 'msg'>Hi, how are you?</div>
</div>
<div class = 'msg-container other'>
<div class = 'msg'>Me? I'm fine. How are you doing?</div>
</div>
<div class = 'msg-container me'>
<div class = 'msg'>Same here.</div>
</div>
<div class = 'msg-container other'>
<div class = 'msg'>OK, bye</div>
</div>
<div class = 'msg-container me'>
<div class = 'msg'>Bye</div>
</div>
</div>
</div>
推荐阅读
- python - 在 python ex25.py 中得到不同的输出。来自Learn python the hardway.python 3.6
- c# - 特殊字符给使用 C# 解析 xml 带来问题
- static - Chapel 中的静态类字段
- ios - 在iOS中反应原生谷歌登录失败反应原生
- sql - 如何在 Tedious 中运行 sql 查询,为 sql in 运算符提供多个值?
- python - 如何在 RGB 颜色检测中使用“if 条件”?
- javafx - Gluon 场景生成器冻结
- javascript - 在 bind() 中如何处理“new”运算符?
- java - java - 如何使带有计数器的java中的android应用程序每24小时自动将整数递增1?
- javascript - 在 React 中更新全局变量/状态