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

为什么display:table用px可居中元素,改用vw/vh单位就失效?

问题根因

该居中方案失效和vh、vw单位没有关联,本质是display: table的居中写法不完整导致的:

  • 仅父元素设置display: table无法实现内部元素居中,需要给子元素额外设置display: table-cell,再配合vertical-align: middle实现垂直居中、text-align: center实现水平居中。
  • 你之前用px单位时显示正常属于巧合:当时20vw/20vh计算后的实际像素值刚好和你测试的固定px值适配,才产生了单位导致失效的错觉。

你遇到的偏移效果如下图:
效果示意图

table布局修复代码

<div
  style={{
   width: '20vw',
   height: '20vh',
   backgroundColor: "black",
   backgroundSize: "100% 100%",
   color: 'white',
   display: 'table'
  }}
>
 <span style={{ 
  fontSize: 30,
  display: 'table-cell',
  verticalAlign: 'middle',
  textAlign: 'center'
}}>Some text</span>
</div>

更推荐的Flex居中方案

目前主流场景更建议使用Flex布局实现居中,代码更简洁,无需额外修改子元素样式:

<div
  style={{
   width: '20vw',
   height: '20vh',
   backgroundColor: "black",
   backgroundSize: "100% 100%",
   color: 'white',
   display: 'flex',
   justifyContent: 'center',
   alignItems: 'center'
  }}
>
 <span style={{ fontSize: 30}}>Some text</span>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:06:00