JSX+Tailwind卡片组件图片无法居中的问题求助
解决Next.js + Tailwind卡片图片居中问题
你的问题出在Next.js的Image组件默认样式上——虽然父容器加了text-center,但Image组件渲染后的元素并不会自动继承文本居中效果,需要显式添加水平居中的Tailwind类。
快速修复方案
给每个Image组件添加className="mx-auto"即可实现居中:
<Image src={design} width={100} height={100} className="mx-auto" />
原理说明
mx-auto对应CSS的margin-left: auto; margin-right: auto;,能让块级元素在父容器中水平居中。- Next.js的
Image组件在指定width和height后会渲染为块级元素,正好适配这个类的效果。
修改后的完整代码
<section> <div> <h3 className='text-3xl py-10 text-center'>About Me </h3> <p className='text-center text-md py-2 leading-8 text-gray-800'> Blah blah blah <span className="text-teal-500 text-md">Tech</span> blah </p> </div> <div className='lg:flex gap-10 '> <div className='text-center shadow-lg p-10 rounded-xl my-10'> <Image src={design} width={100} height={100} className="mx-auto" /> <h3 className='text-lg font-medium pt-8 pb-2'>Beautiful designs</h3> <p className='py-2'> Creating elegant designs suited for your needs </p> <h4 className='py-4 text-teal-600'>Design tools I use</h4> <p className='text-gray-800 py-1'>photoshop</p> <p className='text-gray-800 py-1'>Aftereffects</p> <p className='text-gray-800 py-1'>Blender</p> <p className='text-gray-800 py-1'>Figma</p> </div> <div className='text-center shadow-lg p-10 rounded-xl my-10'> <Image src={design} width={100} height={100} className="mx-auto" /> <h3 className='text-lg font-medium pt-8 pb-2'>Beautiful designs</h3> <p className='py-2'> Creating elegant designs suited for your needs </p> <h4 className='py-4 text-teal-600'>Design tools I use</h4> <p className='text-gray-800 py-1'>photoshop</p> <p className='text-gray-800 py-1'>Aftereffects</p> <p className='text-gray-800 py-1'>Blender</p> <p className='text-gray-800 py-1'>Figma</p> </div> <div className='text-center shadow-lg p-10 rounded-xl my-10 '> <Image src={design} width={100} height={100} className="mx-auto" /> <h3 className='text-lg font-medium pt-8 pb-2'>Beautiful designs</h3> <p className='py-2'> Creating elegant designs suited for your needs </p> <h4 className='py-4 text-teal-600'>Design tools I use</h4> <p className='text-gray-800 py-1'>photoshop</p> <p className='text-gray-800 py-1'>Aftereffects</p> <p className='text-gray-800 py-1'>Blender</p> <p className='text-gray-800 py-1'>Figma</p> </div> </div> </section>
替代方案(灵活布局)
如果需要用Flex布局控制,也可以给图片套一层容器并添加flex justify-center类:
<div className="flex justify-center"> <Image src={design} width={100} height={100} /> </div>
内容的提问来源于stack exchange,提问作者HJTCH76
相关产品推荐
相关产品推荐

