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

如何实现用作模态框关闭按钮的a标签内部X文字垂直居中?

问题核心原因

<a> 标签默认为行内元素,你设置的 height 属性默认不会生效,同时缺少垂直居中的布局规则,因此内部的「X」无法实现垂直居中。

解决方法

方案1(推荐,适配性更强)

给 .close-button 新增flex布局相关属性,无需手动匹配行高,后续修改按钮尺寸或字体大小时也能自动保持居中:

.close-button {
  height: 30px;
  width: 30px;
  background-color: var(--light-color);
  color: var(--main-red);
  margin-left: 0.5em;
  border: 2px solid var(--main-red);
  border-radius: 50%;
  font-weight: 700;
  /* 新增以下3行代码 */
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

方案2(传统行高方案)

设置行高等于按钮高度,同时修改元素类型让宽高生效:

.close-button {
  height: 30px;
  width: 30px;
  background-color: var(--light-color);
  color: var(--main-red);
  margin-left: 0.5em;
  border: 2px solid var(--main-red);
  border-radius: 50%;
  font-weight: 700;
  text-align: center;
  /* 新增以下2行代码 */
  display: inline-block;
  line-height: 30px;
}

额外优化建议

建议把HTML中X两侧的多余空格删掉,避免多余字符影响居中效果:

<a class="close-button close-modal" href="#!">X</a>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:48:00