React+Tailwind CSS固定图片后布局异常:图片全屏/内容被遮挡求助
问题排查:React + Tailwind CSS 固定图片后宽度异常及元素遮挡问题
问题原因分析
- 给背景图容器添加
fixed定位后,元素会脱离文档流,默认以浏览器视口为定位基准,不再受父级col-span-2的宽度约束,因此会撑满整个屏幕宽度。 fixed定位元素的层级默认与普通元素一致,但由于它脱离了文档流,会覆盖后续处于正常文档流中的col-span-1内容块。
解决方案
1. 限制固定图片的宽度范围
给父级col-span-2的容器添加relative(辅助定位参考),同时给背景图容器设置响应式的定位宽度,确保在大屏下仅占据2列的宽度:
- 背景图容器添加
fixed inset-y-0 left-0 lg:right-[33.333%],lg:right-[33.333%]对应3列布局中1列的宽度占比,让图片只覆盖2列区域。 - 保留
bg-cover bg-center确保图片显示效果。
2. 提升内容块的层级
给col-span-1的content-wraper添加relative z-10,让内容块的层级高于固定图片,避免被遮挡。
修改后的完整代码
<div className="h-[100vh]"> <div className="lg:grid grid-cols-3 w-full h-full"> {/* 左侧图片容器 */} <div className="col-span-2 h-full lg:block hidden relative bg-gray-500"> <div className="fixed inset-y-0 left-0 lg:right-[33.333%] bg-cover bg-center" style={{ backgroundImage: `url(${img})` }} ></div> </div> {/* 右侧内容容器 */} <div id="content-wraper" className="col-span-1 bg-white h-full relative z-10"> <div className="left-0 boor">salut</div> <div className="flex items-center justify-center"> <div id="main-content" className="max-w-sm h-full"> <div className="flex items-center justify-center p-10"> <img src={logo} className="block h-[50px] w-auto" alt="" /> </div> <div> <h6 className="text-gray-800 font-semibold text-2xl mb-5 text-center"> Connexion </h6> </div> <div className="mb-5"> <IndexPage /> <Separator text="ou" /> <Boutton /> </div> <div className="mb-5"> <p className="font-light text-gray-400 text-center text-xs"> En continuant, vous acceptez les{" "} <a className="font-medium">Conditions d'Utilisation</a> et la{" "} <a className="font-medium">Politique de Confidentialité</a> de la société. </p> </div> <div className="flex flex-col justify-center items-center text-sm"> <p className="font-medium text-gray-800"> Vous n'êtes pas encore inscrit ? </p> <a href="/auth/sign-up/default" className="font-medium text-yellow-500" > Créer un compte </a> </div> </div> </div> </div> </div> </div>
内容的提问来源于stack exchange,提问作者jawher
相关产品推荐
相关产品推荐

