【居中】相对定位 + 绝对定位 或 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 容易适配多行文字,响应式方便
相关推荐
开开心心_Every1 天前
专业视频修复软件,简单操作效果好
学习·elasticsearch·pdf·excel·音视频·memcache·1024程序员节
liu****2 天前
16.udp_socket(三)
linux·开发语言·数据结构·c++·1024程序员节
草莓熊Lotso2 天前
《算法闯关指南:优选算法--位运算》--38.消失的两个数字
服务器·c++·算法·1024程序员节
unable code3 天前
攻防世界-Misc-can_has_stdio?
网络安全·ctf·misc·1024程序员节
思茂信息3 天前
CST License(Flexnet)设置与问题处理方法
服务器·网络·单片机·3d·php·1024程序员节·cst
2301_797892833 天前
论文阅读:《Hypergraph Motif Representation Learning》
论文阅读·1024程序员节
CoderYanger3 天前
前端基础——CSS练习项目:百度热榜实现
开发语言·前端·css·百度·html·1024程序员节
liu****4 天前
13.POSIX信号量
linux·开发语言·c++·算法·1024程序员节
liu****4 天前
12.线程同步与互斥
linux·数据结构·c++·算法·1024程序员节
CoderJia程序员甲4 天前
GitHub 热榜项目 - 日榜(2025-11-08)
ai·开源·github·1024程序员节·ai教程