You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在响应式样机图片上定位文字 实现居中和响应式适配

响应式样机图固定区域文字定位方案

固定像素偏移无法适配响应式缩放的核心原因是,偏移值不会随图片尺寸等比例变化,且未给绝对定位设置正确的定位基准。按以下方式修改即可实现文字始终居中在搜索栏、随图同步缩放:

  • 给同时包裹图片和目标文字的直接父元素添加position: relative,作为绝对定位的偏移基准,避免文字相对于页面其他元素错位
  • 废弃固定像素的left/top偏移值,改用百分比定位+transform实现位置匹配:水平方向用left:50%+transform:translateX(-50%)实现水平居中,垂直方向按搜索栏在图片中的实际占比设置百分比偏移(当前样机图设置top:22%即可刚好落在搜索栏区域)
  • 给文字设置与搜索栏等比例的宽度(当前样机图搜索栏占图宽62%,直接给文字设width:62%+text-align:center即可保证文字在栏内居中)
  • 废弃固定像素字号,改用clamp()设置响应式字号,让文字大小随容器尺寸同步缩放,避免大小失配
  • 将图片设置为块级元素、宽度100%高度自适应,消除行内元素默认边距导致的位置计算误差

修正后完整代码

CSS部分

.mockup-wrap {
  position: relative;
  width: 100%;
}
.mockup-wrap img {
  width: 100%;
  height: auto;
  display: block;
}
#text {
  position: absolute;
  z-index: 100;
  color: black;
  font-weight: bold;
  margin: 0;
  /* 水平居中 */
  left: 50%;
  transform: translateX(-50%);
  /* 匹配搜索栏垂直位置 */
  top: 22%;
  /* 响应式字号:最小12px,随宽度缩放,最大24px */
  font-size: clamp(12px, 2vw, 24px);
  /* 匹配搜索栏宽度 */
  width: 62%;
  text-align: center;
}

HTML部分

<script src="https://cdn.tailwindcss.com"></script>
<div class="flex flex-wrap w-full justify-center content-center px-12">
    <div class="flex flex-wrap lg:items-center min-h-screen">
        <div class="flex flex-col w-full lg:w-1/2 justify-center mockup-wrap">
            <img src="https://i.imgur.com/sb5Jz5I.png" class="object-contain max-h-full">
            <p id="text">Dynamic text!</p>
        </div>
        <div class="flex flex-wrap w-full lg:w-1/2 justify-center">
            <h3 class="text-3xl">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</h3>
        </div>
    </div>
</div>

如果后续更换样机图,仅需微调top和width的百分比值,匹配新图中搜索栏的垂直位置和宽度占比即可,无需修改其他逻辑。

内容的提问来源于stack exchange,提问作者tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 14:45:32