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

使用line-height实现CSS居中时p标签与div容器存在间隙问题咨询

问题原因

  • 浏览器给<p>标签设置了默认的上下外边距,这是间隙的核心来源
  • 父级.center设置的line-height:200px会被作为inline-block元素的<p>继承,多余的行高也会额外撑出间隙

修复方案

你只需要给.center p规则补充两个属性即可:重置默认外边距、把p元素自身的行高改成正常大小,修正后的CSS如下:

.center {
  line-height: 200px;
  height: 200px;
  border: 3px solid green;
  text-align: center;
}
.center p {
  display: inline-block;
  vertical-align: middle;
  background-color: green;
  /* 新增以下两行 */
  margin: 0;
  line-height: normal;
}

对应的HTML代码无需修改。
如果还有其他场景需要类似居中效果,也可以直接给父级开启flex布局,兼容性已经覆盖绝大多数场景:

.center {
  height: 200px;
  border: 3px solid green;
  display: flex;
  align-items: center;
  justify-content: center;
}
.center p {
  background-color: green;
  margin: 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:06:04