如何用Tailwind CSS在嵌套div中实现内容垂直水平居中
解决Tailwind CSS嵌套div内内容垂直水平居中问题
你的代码里有两个关键问题导致居中失效:
1. 类名拼写错误
你写的item-center是错误的,Tailwind中控制flex子元素垂直居中的类是**items-center**(复数形式)。
2. 容器未占满父级高度
#home所在的div没有占据父级.grow容器的全部高度,flex垂直居中需要容器有足够的高度空间才能生效,所以需要给#home添加h-full类,让它填满父级的剩余高度。
修正后的完整代码
<div class="flex flex-col items-center min-h-screen"> <header class="flex-none text-center w-full"> <p>Header</p> </header> <div class="grow w-full"> <div id="home" class="flex justify-center items-center h-full"> <main> <p>Shall be vertical and horizontal center.</p> </main> </div> </div> <footer class="flex-none text-center m-2 w-full"> <hr class="mx-auto mb-2 sm:w-56 w-36 h-0.5 bg-gray-100 rounded border-0 shadow-2xl" /> <div class="flex sm:flex-row flex-col sm:gap-4 gap-1 justify-center text-sm font-light"> <p>Footer</p> </div> </footer> </div>
关键改动说明
- 将
item-center改为items-center,实现垂直方向居中 - 给
#home添加h-full,让容器铺满父级.grow的全部高度,确保垂直居中的空间足够
内容的提问来源于stack exchange,提问作者Pantastisch
相关产品推荐
相关产品推荐

