【居中】相对定位 + 绝对定位 或 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 容易适配多行文字,响应式方便
相关推荐
Be for thing26 分钟前
PyTorch自动求导Autograd详解|requires_grad、backward、grad、梯度清零
pytorch·学习·1024程序员节
syagain_zsx37 分钟前
ODB 与 MySQL:C++ 里的 ORM 实践(类即表、事务铁律与查询封装)
开发语言·数据库·c++·mysql·工具库·1024程序员节
小嘉丶学长40 分钟前
Day08 · 字符串(二)
服务器·开发语言·python·学习·1024程序员节
4SAPI1 小时前
电商全链路内容自动化生成大模型 API 生产选型指南:4SAPI、硅基流动与 OpenRouter 的架构权衡
运维·人工智能·架构·自动化·1024程序员节
深圳老胡1 小时前
STM32F103 硬件 SPI 与软件 IO 模拟 SPI 最高速度差异详解
笔记·stm32·单片机·代码规范·1024程序员节
CappuccinoRose2 小时前
滚动交互体系
前端·javascript·交互·html5·1024程序员节
画中有画2 小时前
论可观测性架构在分布式系统中的应用
1024程序员节
惊讶的猫2 小时前
慢查询和排查方式(查询日志 + 分析工具 + EXPLAIN)
mysql·1024程序员节
John_Hui3 小时前
MySQL基础知识
数据库·sql·mysql·1024程序员节
淡海水3 小时前
07-06-源码-.NET Core GC的极致优化技术
unity·架构·c#·.netcore·gc·1024程序员节