React/CSS求助:如何将文字定位在图片上方并在父div内居中
问题根因
你给文字设置position: absolute后,没有给它的直接父容器设置定位基准,绝对定位元素默认会以整个页面视口为参照定位,所以才会出现文字相对于页面居中的问题,和你设置的top:50%、left:50%属性本身无关。
解决方法
只需要两步修改即可实现父容器内居中效果:
- 给包裹图片和文字的父div添加
position: relative属性,让内部绝对定位的元素以这个父容器为定位基准 - 修正flex布局的属性拼写,可额外加
gap调整两个名字的间距、给h1清除默认外边距避免布局偏移
修改后的完整代码如下:
<div style={{ display: `flex`, flexDirection: `column` }}> {/* image and title */} {/* 给父容器加position: relative作为定位基准 */} <div style={{position: 'relative'}}> <StaticImage src="../images/home.png" width={1000} quality={100} formats={["auto", "webp", "avif"]} alt="home image" style={{ marginBottom: `1rem` }} /> <div style={{ position: `absolute`, top: `50%`, left: `50%`, transform: `translate(-50%, -50%)`, zIndex: 2, display: `flex`, flexDirection: `row`, justifyContent: `center`, gap: '3rem', /* 按需调整两个名字的间距大小 */ }}> <h1 style={{ color: `white`, fontSize: `7vw`, margin: 0 /* 清除浏览器默认标题外边距 */ }}>Gareth</h1> <h1 style={{ color: `white`, fontSize: `7vw`, margin: 0 }}>Veale</h1> </div> </div> </div>
内容的提问来源于stack exchange,提问作者0xgareth
相关产品推荐
相关产品推荐

