如何实现图片上方文本居中且窗口缩放时位置保持不变?
解决方法
要实现文本在图片内部居中且随窗口缩放保持居中,核心是让绝对定位的文本以图片容器为基准进行定位,同时通过transform修正偏移,避免固定值导致的错位。以下是具体调整方案:
关键样式修改
1. 调整图片容器布局
将.subtitle改为相对定位+行内块元素,让容器宽度自适应图片大小,同时方便整体水平居中:
.subtitle { position: relative; display: inline-block; /* 容器宽度由图片决定 */ margin: 0.5rem auto; /* 水平居中容器 */ }
2. 修正文本定位逻辑
通过left:50% + top:50%将文本左上角移到容器中心,再用transform将文本自身中心与容器中心重合,同时添加防溢出处理:
.subtitle .subtitle-text{ position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); /* 向左向上偏移自身宽高的50%,实现完美居中 */ text-align: center; color: #fff; font-weight: 900; font-size: 0.8rem; font-family: b; width: 100%; /* 文本宽度匹配图片容器 */ padding: 0 5px; /* 左右留边避免文本溢出图片 */ box-sizing: border-box; /* 内边距计入宽度,防止撑开容器 */ }
3. 辅助调整
给.main添加text-align:center,确保图片容器在页面水平居中;给图片添加display:block移除默认行内间距。
修改后的完整代码
<html> <head> <title>Title</title> <link rel="stylesheet" type="text/css" href="style.css"> <style> .title { position: absolute; text-align: center; color: #fff; font-weight: 900; font-size: 1rem; font-family: b; } .fa { position: relative; display: flex; align-items: center; justify-content: center; margin-bottom: 1rem; } .fa img { width: 30%; height: 1.5rem; display: block; margin: 0 auto; } .subtitle { position: relative; display: inline-block; margin: 0.5rem auto; } .subtitle img { width: 23%; display: block; /* 移除图片默认行内间距 */ } .subtitle .subtitle-text{ position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); text-align: center; color: #fff; font-weight: 900; font-size: 0.8rem; font-family: b; width: 100%; padding: 0 5px; box-sizing: border-box; } .main { padding: 1rem 0; overflow-x: hidden; text-align: center; /* 让图片容器水平居中 */ } .main .box{ width: 100%; margin: 0 auto; text-align: center; color: #292B32; margin-right: 1.5rem; font-size: 0.65rem; font-weight: 400; font-family: b; } </style> </head> <body> <div class="main"> <div class="fa"> <div class="title">title</div> <img src="https://www.researchgate.net/profile/Maximus-Tamur/publication/354575794/figure/fig2/AS:1067950245154821@1631630588806/Rectangle-b-Cut-out-the-existing-rectangular-shape-through-one-of-the-diagonal-lines-c.png" alt="" /> </div> <div class="cont"> <div class="subtitle"> <div class="subtitle-text">subtext</div> <img src="https://www.researchgate.net/profile/Maximus-Tamur/publication/354575794/figure/fig2/AS:1067950245154821@1631630588806/Rectangle-b-Cut-out-the-existing-rectangular-shape-through-one-of-the-diagonal-lines-c.png" alt="" /> </div> </div> </div> </body> </html>
核心逻辑说明
- 相对定位的
.subtitle作为文本的定位基准,确保文本始终以图片所在区域为参照 left:50% + top:50%将文本左上角移到容器中心,transform: translate(-50%, -50%)修正偏移,让文本自身中心与容器中心重合,实现自适应居中- 宽度设置和内边距避免文本长度超过图片宽度时溢出容器
内容的提问来源于stack exchange,提问作者Yesha
相关产品推荐
相关产品推荐

