可滚动Flex子元素随兄弟元素展开自动收缩的实现方案
解决方案
一、纯CSS实现(推荐)
完全可以用纯CSS解决,问题根源是你给.typing-area加了position:absolute,让它脱离了flex布局的文档流,导致.chat-area的flex布局无法自动分配空间。只需要调整几个样式:
修改后的CSS代码
* { margin: 0; padding: 0; box-sizing: border-box; } html { font-size: 62.5%; } body { background-color: #fff; display: flex; align-content: center; justify-content: center; margin-top: 5rem; } .wrapper-chat { display: flex; align-items: start; justify-content: center; width: 40rem; height: 34rem; } .chat-area { width: 100%; height: 100%; display: flex; flex-direction: column; /* 移除不必要的相对定位 */ } .chat-area header { height: 5rem; background-color: green; } .chat-box { flex-grow: 1; overflow-y: auto; /* 移除固定max-height,让flex自动分配剩余空间 */ padding: 1rem 3rem 2rem 3rem; background: white; border: 0.5rem solid #b8b6b6; font-size: 15px; font-weight: 400; line-height: 1; /* 可选:限制聊天框最小高度,避免输入框过高时聊天框消失 */ min-height: 10rem; } .typing-area { padding: 1.8rem 3rem; display: flex; /* 移除绝对定位相关属性,让它作为flex子项参与布局 */ background-color: green; } .typing-area .input-field { display: block; min-height: 4.5rem; max-height: 20rem; width: 100%; overflow-y: auto; font-size: 1.6rem; padding: 1rem 2rem; border: 2px solid whitesmoke; border-radius: 0.5rem; line-height: 20px; background-color: white; }
原理说明
.chat-area是flex-direction: column的容器,子项包括header、chat-box、typing-area.chat-box设置flex-grow:1,会自动占据header和typing-area之外的所有剩余空间- 当
.input-field输入多行内容导致.typing-area高度增加时,flex容器会自动压缩.chat-box的空间,overflow-y:auto让聊天内容超出时滚动,完美实现自动收缩效果
二、JavaScript实现(仅当必须保留绝对定位时使用)
如果因为特殊布局需求必须保留.typing-area的绝对定位,可以用JS监听输入框的高度变化,动态调整.chat-box的最大高度:
代码实现
const inputField = document.querySelector('.input-field'); const chatBox = document.querySelector('.chat-box'); const chatArea = document.querySelector('.chat-area'); const header = document.querySelector('.chat-area header'); // 计算并更新聊天框可用高度 function updateChatBoxHeight() { const totalHeight = chatArea.offsetHeight; const headerHeight = header.offsetHeight; const typingAreaHeight = document.querySelector('.typing-area').offsetHeight; chatBox.style.maxHeight = `${totalHeight - headerHeight - typingAreaHeight}px`; } // 初始化时执行一次 updateChatBoxHeight(); // 监听输入框内容变化 inputField.addEventListener('input', updateChatBoxHeight); // 监听窗口大小变化(如果容器高度可能随窗口改变) window.addEventListener('resize', updateChatBoxHeight);
原理说明
- 通过监听输入框的
input事件,实时获取.typing-area的当前高度 - 用
.chat-area的总高度减去header和输入区域的高度,得到.chat-box的可用最大高度并动态赋值 - 同时监听窗口resize事件,确保窗口大小变化时布局依然正常
内容的提问来源于stack exchange,提问作者electronixG
相关产品推荐
相关产品推荐

