【居中】相对定位 + 绝对定位 或 Flexbox 居中

方法一:相对定位 + 绝对定位

关键代码:

bash 复制代码
父:position: relative"
子:  position: absolute;
     top: 50%;
     left: 50%;
     transform: translate(-50%, -50%);
bash 复制代码
 <button style="background: none;border: none;position: relative">     
      <img src="https://youke1.picui.cn/s1/2025/10/24/68fb0cabaa3af.png" width="233px" height="51px"/>
     <span style="
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    font-weight: bold;
    pointer-events: none; /* 不阻止按钮点击 */
  ">Repay now</span>
    </button>

方法二:Flexbox 居中

说明:

按钮用 Flexbox 容器居中内容

图片绝对定位覆盖按钮背景

文字自动居中

bash 复制代码
<button>
  background: none;
  border: none;
  padding: 0;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 233px;
  height: 51px;
">
  <img src="https://youke1.picui.cn/s1/2025/10/24/68fb0cabaa3af.png" style="position: absolute; width: 100%; height: 100%; " />
  <span style="color: white; font-weight: bold; z-index: 1">Cancel</span>
</button>

3、总结

方法 特点
相对 + 绝对定位 精准控制文字位置,适合单行文字
Flexbox 容易适配多行文字,响应式方便
相关推荐
开开心心就好1 天前
内存清理工具开源免费,自动优化清理项
linux·运维·服务器·python·django·pdf·1024程序员节
张萌杰4 天前
深度学习的基础知识(常见名词解释)
人工智能·深度学习·机器学习·1024程序员节
开开心心就好5 天前
免费无广告卸载工具,轻便安全适配全用户
linux·运维·服务器·网络·安全·启发式算法·1024程序员节
开开心心就好6 天前
图片格式转换工具,右键菜单一键转换简化
linux·运维·服务器·python·django·pdf·1024程序员节
徐子童8 天前
网络协议---TCP协议
网络·网络协议·tcp/ip·面试题·1024程序员节
扫地的小何尚10 天前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
数据皮皮侠AI11 天前
上市公司股票名称相似度(1990-2025)
大数据·人工智能·笔记·区块链·能源·1024程序员节
开开心心就好11 天前
系统清理工具清理缓存日志,启动卸载管理
linux·运维·服务器·神经网络·cnn·pdf·1024程序员节
Evan东少14 天前
[踩坑]笔记本Ubuntu20.04+NvidiaRTX5060驱动+cuda+Pytorch+ROS/Python实现人脸追踪(环境准备)
1024程序员节
不爱编程的小陈15 天前
C/C++每日面试题
面试·职场和发展·1024程序员节