如何使用Tailwind CSS将Div对齐到h-screen容器底部?
解决方法:将Div对齐到h-screen容器底部
要实现目标,核心是给带h-screen的容器添加flex垂直布局,因为mt-auto只有在flex容器内才能生效,自动将元素推至底部。具体修改如下:
- 给目标容器(
<div class="bg-black h-screen ...">)添加flex flex-col类,让子元素垂直排列 - 移除目标div上多余的
content-end align-bottom类,这些在flex-col布局下无需额外设置
修改后的完整代码:
<div> <div class="flex"> <div class="bg-black h-screen p-5 pt-8 relative duration-300 flex flex-col" :class="{ 'w-72': open, 'w-20': !open }"> <div @click="toggleMenu"> <outline-arrow-left-icon v-if="open" class="w-6 h-6 bg-white text-black rounded-full absolute -right-2.5 border-black cursor-pointer" /> <outline-arrow-right-icon v-if="!open" class="w-6 h-6 bg-white text-black rounded-full absolute -right-2.5 border-black cursor-pointer" /> </div> <div class="inline-flex"> <img src="https://via.placeholder.com/40" class="block rounded-full cursor-pointer float-left mr-2"/> <h2 class="transform text-white font-medium origin-left text-2xl m-auto duration-300" :class="{'scale-0': !open}">Brand</h2> </div> <div class="mt-auto flex cursor-pointer"> <div class="text-white"> Test </div> </div> </div> <div class="p-7 w-full"> <Nuxt/> </div> </div>
原理说明
原容器默认是display:block,mt-auto在块级元素中只会设置margin-top为auto,但无法利用剩余空间将元素推到底部。而当容器设置为flex flex-col后,子元素会处于垂直flex流中,mt-auto会自动占据上方所有剩余空间,从而将目标div固定在容器底部。
内容的提问来源于stack exchange,提问作者Sander Bakker
相关产品推荐
相关产品推荐

