如何让main与div#undermain占据布局剩余高度?
如何让main及子元素占据布局剩余高度(Tailwind实现)
我尝试让main元素和div#undermain占据布局的剩余高度,但没能实现,使用Tailwind的代码如下:
<body> <div class="min-h-screen w-screen overflow-auto bg-black"> <nav class="flex w-full items-center justify-start gap-3 border-b-2 border-b-gray-800 py-3 pr-6 pl-3" > <img src="./someurl.svg" /> <h1 class="text-2xl text-green-500">Delivert</h1> </nav> <main class="h-full w-full"> <div id="undermain" class="flex h-full w-full items-center justify-center"> <button class="bg-green-500"> sign in </button> </div> </main> </div> </body>
我知道flexbox是解决这类问题的常用方法,自己试出了一个可行方案:
- 给body下的最外层div设置display: flex和flex-direction: column;
- 给main设置flex-grow: 1和display: flex;
- 移除#undermain的height: 100%。
但我觉得这个方案不符合CSS规范,想知道更合理的实现方式。
其实这个方案完全符合CSS规范,flexbox就是专门用来处理这种弹性布局场景的。下面是用Tailwind工具类直接实现的优化代码:
<body> <div class="min-h-screen w-screen overflow-auto bg-black flex flex-col"> <nav class="flex w-full items-center justify-start gap-3 border-b-2 border-b-gray-800 py-3 pr-6 pl-3" > <img src="./someurl.svg" /> <h1 class="text-2xl text-green-500">Delivert</h1> </nav> <main class="flex-grow flex w-full"> <div id="undermain" class="flex w-full items-center justify-center"> <button class="bg-green-500"> sign in </button> </div> </main> </div> </body>
实现说明:
- 最外层div添加
flex flex-col类,让nav和main两个子元素按垂直方向排列; - 给main添加
flex-grow类,对应CSS的flex-grow: 1,让它自动占据nav以外的所有剩余高度; - main设置
flex类,使其成为flex容器,此时子元素#undermain会默认拉伸填充容器高度,不需要额外设置h-full,直接用flex items-center justify-center就能实现内容居中。
内容的提问来源于stack exchange,提问作者chocojunkie
相关产品推荐
相关产品推荐

