首页 > 解决方案 > 如何将新的子元素和滚动条附加到父 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;
}

考虑到有多少网站有某种聊天界面,我不觉得这是一个不常见的要求,但我还没有找到任何可行的解决方案。

标签: cssflexboxchat

解决方案


尝试将其包装在容器中:

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>


推荐阅读