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

如何在响应式Div内底部20px处居中文字并适配窗口

解决方案

一、HTML 修改(<h5> 标签放置位置)

将 <h5> 标签放在米色 <div> 内部,与 <img> 同级,同时补全 <img> 标签的闭合符号:

<html>
  <head>
<link rel="stylesheet" type="text/css" href="styles.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  </head>
 <body>
    <div>
      <img src="https://loiz.xyz/loiz.gif" />
      <h5>你的文字内容</h5>
    </div>

<style type="text/css"> html, body {margin: 0; height: 100%; overflow: hidden}</style>
 </body>
</html>

二、CSS 调整

1. 修改现有 <div> 的样式

给米色div添加 position: relative,让内部绝对定位的元素以该div为参考容器:

div {
  width: calc(100% - 40px);
  height: calc(100% - 40px);
  background: #f0e8e6;
  overflow: hidden;
  margin: auto;
  display: flex;
  position: relative; /* 新增 */
}

2. 添加 <h5> 的专属样式

通过绝对定位固定在div底部20px处,实现自适应居中与字号:

h5 {
  position: absolute;
  bottom: 20px; /* 距离div底部20px */
  left: 50%;
  transform: translateX(-50%); /* 水平居中,适配任意窗口宽度 */
  margin: 0; /* 清除h5默认的上下外边距,避免位置偏移 */
  font-size: 2vw; /* 基于视口宽度的自适应字号,可根据需求调整数值 */
  text-align: center; /* 双重保障文字居中 */
  color: #333; /* 可选:设置文字颜色,与米色背景区分 */
}

关键说明

  • 给div设置 position: relative 作为定位上下文,确保h5的绝对定位不会脱离米色容器;
  • left:50% + transform: translateX(-50%) 是自适应场景下最可靠的居中方案,窗口缩放后仍能保持居中;
  • vw 单位让字号随窗口宽度自动调整,无需额外脚本;
  • 清除h5默认margin可保证与底部的间距精准为20px,避免偏移。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:01:03