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

如何让圆形关闭按钮内mark div的文本实现水平垂直居中

方案1:现有代码最小改动

你当前的.mark已经完全撑满父按钮容器,只需要补充文本居中规则即可:

.close-button .mark {
  position: absolute;
  width: 100%;
  height: 100%;
  margin: 0;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /* 新增规则 */
  text-align: center;
  line-height: 5em;
}

line-height取值和按钮高度保持一致即可实现单行文本垂直居中,适合不需要后续修改按钮尺寸的场景。


方案2:自适应flex实现(推荐)

不需要绑定按钮固定高度,后续修改按钮尺寸无需同步调整居中规则:

.close-button .mark {
  position: absolute;
  width: 100%;
  height: 100%;
  margin: 0;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /* 新增规则 */
  display: flex;
  align-items: center;
  justify-content: center;
}

方案3:冗余代码优化方案

其实不需要给.mark添加绝对定位,直接在父级按钮上做居中处理即可,代码更简洁:

.close-button {
  margin-top: auto;
  padding: 0;
  cursor: pointer;
  border: none;
  border-radius: 5rem;
  background: black;
  color: white;
  position: relative;
  width: 5em;
  height: 5em;
  /* 新增规则,直接在父容器完成居中 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-button .mark {
  margin: 0;
}
<button class="close-button">
  <div class="mark">+</div>
</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:24:08