如何让主div两侧的相邻div占据剩余空间且不挤压主内容?
纯Tailwind CSS解决方案
可以直接用Tailwind的响应式类和flex布局属性实现,无需额外自定义CSS:
<main class="flex"> <!-- 左侧占位区域 --> <div class="hidden lg:flex-1">left white area</div> <!-- 主内容区域 --> <div class="flex justify-center max-w-xl bg-purple-400"> ... 主内容 ... </div> <!-- 右侧占位区域 --> <div class="hidden lg:flex-1">right white area</div> </main>
关键说明:
- 这里的
lg断点对应你当前媒体查询的64rem(1024px),如果你的max-w-xl对应其他断点,替换成对应的Tailwind断点类即可(比如xl对应1280px)。 flex-1属性会让左右div自动占据主内容区域以外的剩余空间,并且自动平分宽度,不需要手动计算calc。- 默认用
hidden隐藏左右区域,当屏幕宽度达到断点时显示,完全符合你的需求。
如果需要让左右区域在所有超过主内容宽度的屏幕下都显示,也可以调整为:
<main class="flex"> <div class="flex-1 invisible lg:visible">left white area</div> <div class="flex justify-center max-w-xl bg-purple-400"> ... 主内容 ... </div> <div class="flex-1 invisible lg:visible">right white area</div> </main>
这种方式下,小屏幕时左右区域仍占据空间但不可见,大屏时显示内容,根据你的实际需求选择即可。
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

