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

如何在Bootstrap中居中modal-title标题?

解决Bootstrap中Modal标题(modal-title)居中的问题

这问题我之前也碰到过!核心原因是Bootstrap 4正式版和beta版本的布局逻辑不一样——正式版里.modal-header默认用了Flexbox布局,直接沿用beta版的margin: auto自然达不到预期效果。

为什么原来的方法失效了?

Bootstrap 4正式版里,.modal-header的默认样式是这样的:

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem;
  border-bottom: 1px solid #dee2e6;
}

同时.modal-title默认带有flex-grow: 1属性,会自动占据关闭按钮之外的所有空间。这时候给标题加margin: auto,只会让它在自己的“专属空间”里居中,而不是整个header的中间。

两种快速解决的方案:

方案1:调整整个header的对齐方式

直接修改.modal-header的Flex对齐规则,让内部元素居中:

.modal-header {
  justify-content: center;
}

要是想保留右上角的关闭按钮,就给按钮加绝对定位,同时让header变成相对定位容器:

.modal-header {
  justify-content: center;
  position: relative;
}
.modal-header .close {
  position: absolute;
  right: 1rem;
  top: 1rem;
}

方案2:修改标题的Flex属性

不想动header布局的话,就给标题取消默认的拉伸属性,再用margin居中:

h5.modal-title {
  flex-grow: 0; /* 不让标题占满剩余空间 */
  margin: 0 auto;
}

把上面任意一种CSS加到你的项目里,再打开模态框,标题就能完美居中啦~

内容的提问来源于stack exchange,提问作者Tommy Hügel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:14:40