【居中】相对定位 + 绝对定位 或 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 容易适配多行文字,响应式方便
相关推荐
开开心心就好7 天前
内存清理软件灵活设置,自动阈值快捷键清
运维·服务器·windows·pdf·harmonyos·risc-v·1024程序员节
学传打活9 天前
【边打字.边学昆仑正义文化】_5_宇宙物种创造简史(1)
微信公众平台·1024程序员节·汉字·昆伦正义文化
xcLeigh10 天前
打破机房围墙:VMware+cpolar构建跨网络虚拟实验室
vmware·内网穿透·cpolar·实验室·远程访问·1024程序员节
开开心心就好11 天前
免费轻量电子书阅读器,多系统记笔记听书
linux·运维·服务器·安全·ddos·可信计算技术·1024程序员节
unable code12 天前
流量包取证-大流量分析
网络安全·ctf·misc·1024程序员节·流量包取证
开开心心就好12 天前
实用PDF擦除隐藏信息工具,空白处理需留意
运维·服务器·windows·pdf·迭代器模式·桥接模式·1024程序员节
unable code13 天前
浏览器取证-[GKCTF 2021]FireFox Forensics
网络安全·ctf·misc·1024程序员节·浏览器取证
unable code13 天前
内存取证-[安洵杯 2019]Attack
网络安全·ctf·misc·1024程序员节·内存取证
unable code14 天前
CTF-SPCS-Forensics
网络安全·ctf·misc·1024程序员节·取证