TailwindCSS实现侧边栏展开项不挤压其他区域并滚动
解决方案
要实现你需要的效果,核心是利用Flex布局让可展开的区块自动占据侧边栏剩余空间,同时限制其内部滚动,避免挤压其他固定高度的蓝色区块。具体修改如下:
修改思路
- 侧边栏容器设置为垂直Flex布局,让内部元素按垂直方向分配空间
- 保持其他蓝色区块的固定高度,确保它们占据固定位置不被挤出
- 给可展开的红色子项容器设置
flex-grow:1,使其自动填充侧边栏剩余空间;添加overflow-y:auto实现内部滚动;再加上min-height:0确保Flex子项能正确收缩(避免内容溢出时撑爆容器)
修改后的代码
<div id="container" class="h-96 w-52 overflow-hidden bg-black flex flex-col"> <div class="h-[100px] w-full border border-black bg-blue-500"></div> <div id="item-container" class="space-y-1 overflow-y-auto flex-grow min-h-0"> <div class="h-10 w-full bg-red-500"></div> <div class="h-10 w-full bg-red-500"></div> <div class="h-10 w-full bg-red-500"></div> <div class="h-10 w-full bg-red-500"></div> <div class="h-10 w-full bg-red-500"></div> <div class="h-10 w-full bg-red-500"></div> </div> <div class="h-20 w-full border border-black bg-blue-500"></div> <div class="h-20 w-full border border-black bg-blue-500"></div> </div> <style> .h-96{ height: 24rem; } .w-52{ width: 13rem; } .overflow-hidden{ overflow: hidden; } .bg-black{ background-color: rgb(0 0 0); } .w-full{ width:100%; } .border{ border-width: 1px; } .border-black{ border-color: rgb(0 0 0); } .bg-blue-500{ background-color: rgb(59 130 246); } .space-y-1{ margin-top: 0.25rem; } .overflow-y-auto{overflow-y: auto;} .h-10{height: 2.5rem;} .bg-red-500{ background-color: rgb(239 68 68); } .h-20{height: 5rem;} .h-\[100px\]{ height:100px; } .flex{ display: flex; } .flex-col{ flex-direction: column; } .flex-grow{ flex-grow: 1; } .min-h-0{ min-height: 0; } </style>
关键修改点
- 给
#container添加flex和flex-col类,启用垂直Flex布局 - 移除
#item-container的h-fit,替换为flex-grow(占满剩余空间)和min-h-0(解决Flex子项内容溢出时无法收缩的问题) - 将
overflow-y-scroll改为overflow-y-auto,只有内容超出时才显示滚动条,更美观
内容的提问来源于stack exchange,提问作者Arsen
相关产品推荐
相关产品推荐

