如何用Tailwind CSS将按钮定位到父div底部并居中对齐
解决方案
要实现按钮固定在卡片底部且居中的效果,只需针对你的代码做两处关键修改:
修改后的完整代码
<div className='md:flex justify-center'> <div className='m-2 p-4 bg-gray-100 border-2 border-gray-300 rounded-lg max-w-md shadow-xl mx-auto md:mx-4 hover:scale-105 duration-150 group relative'> <div className='flex justify-between'> <h1 className='font-bold text-xl'>The[Creators] - NFT Homepage</h1> <a href="https://thecreatorsnft.com" target='_blank' rel="noreferrer"><img src={tcLogo} alt="thecreatorslogo" className='w-14 hover:rotate-12 duration-150' /></a> </div> <p className='py-2'>My first Project was a Homepage, which contains infos about <a href="https://www.janlampert.com" rel="noreferrer" className='text-nevBlue underline font-bold' target="_blank">Jan Lampert's</a> and my NFT Collections. You can find the Link down here 👇.</p> <div className='flex absolute bottom-4 left-0 right-0 justify-center items-end md:scale-0 group-hover:scale-100 duration-150'> <button className='mx-auto rounded-xl bg-cyan-400 hover:shadow-lg hover:shadow-cyan-600 duration-300 py-4 px-6 font-bold text-xl'><a href="https://github.com/nevthereal/TheCreators" target="_blank" rel="noreferrer">Github</a></button> <button className='mx-auto rounded-xl bg-pink-400 hover:shadow-lg hover:shadow-pink-600 duration-300 py-4 px-6 font-bold text-xl'><a href="https://thecreatorsnft.com" target='blank'>Website</a></button> </div> </div> </div>
关键改动说明
- 给卡片容器(外层的
div.group)添加relative类:这是让内部绝对定位元素基于卡片定位的前提,否则绝对定位会相对于整个文档流。 - 修改按钮容器的类:
- 添加
absolute:让按钮容器脱离正常文档流,固定在卡片底部 - 添加
left-0 right-0:让容器宽度铺满卡片,配合justify-center实现内部按钮居中 - 添加
justify-center:让两个按钮在容器内水平居中排列 - 保留原有的
bottom-4:控制按钮容器距离卡片底部的间距
- 添加
这样修改后,按钮栏就会固定在卡片底部,同时保持水平居中,和你参考的效果一致。
内容的提问来源于stack exchange,提问作者Neville Brem
相关产品推荐
相关产品推荐

