实现面板内容按需滚动与高度自适应,不修改.parent CSS样式
解决方案
原代码的核心问题是面板容器设置了固定高度,导致内容较少时无法自动收缩;同时内部子元素依赖父元素固定高度的百分比设置,无法自适应内容高度。以下是修改后的CSS(未修改.parent类):
.parent { } #panel2 { left: 350px; } .apvr-presentation-panel-wrap { position: absolute; top: 30px; left: 0; max-width: 300px; width: 100%; background: #ede; max-height: calc(100% - 60px); height: auto; /* 改为auto,让高度随内容自适应 */ } .apvr-presentation-panel-opened { transform: translateX(0); } .apvr-presentation-panel { position: relative; display: flex; /* 启用flex布局 */ flex-direction: column; /* 垂直排列子元素 */ } .apvr-presentation-content-wrap { overflow-y: auto; overflow-x: hidden; position: relative; flex: 1; /* 占据面板剩余空间,内容过多时触发滚动 */ min-height: 0; /* 解决flex子元素溢出的兼容性问题 */ } .apvr-presentation-content { position: relative; display: flex; flex-direction: column; padding: 20px; box-sizing: border-box; } .apvr-presentation-title { font-weight: 600; font-size: 1.4em; margin: 3px; } .apvr-presentation-desc { font-size: 1em; margin: 3px; }
修改说明:
.apvr-presentation-panel-wrap:将固定height改为auto,使面板高度随内容自动调整,同时保留max-height限制其最大高度,防止内容过多时超出视口。.apvr-presentation-panel:添加flex垂直布局,让内部内容容器能根据内容高度动态分配空间,替代原固定百分比高度的依赖。.apvr-presentation-content-wrap:用flex:1替代height:100%,使其在flex布局中自动填充面板的剩余空间;min-height:0确保在内容不足时容器能正常收缩,同时在内容超出时触发垂直滚动。
HTML无需修改,直接使用原结构即可实现需求:内容少的面板自动收缩高度,内容多的面板在达到最大高度后内部可滚动。
内容的提问来源于stack exchange,提问作者Toniq
相关产品推荐
相关产品推荐

