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

为何Flex的align-items:center与justify-content:center无法让文字居中?

问题分析与解决方案

嘿,这个问题我刚学Flex的时候也踩过坑!咱们来一步步把它捋清楚:

为什么当前代码没生效?

你给.square加了justify-content: center和align-items: center,但这两个属性只有在元素是Flex容器(也就是设置了display: flex)的时候才会生效——你的.square现在只是普通块级元素,所以这俩对齐属性根本没起作用。另外,:before伪元素默认是行内元素,就算容器是Flex,也得先让容器的Flex规则能作用到它。

正确的实现方法

只需要给.square加上display: flex,就能让它的对齐属性生效,把伪元素的文字稳稳居中。另外可以给伪元素加一点样式优化显示效果:

html{ 
  margin: 0px; 
  padding: 0px; 
} 
body{ 
  position: absolute; 
  width: 100%; 
  height: 100%; 
  display: flex; 
  justify-content: center; 
  align-items: center; 
} 
#board { 
  display: flex; 
  flex-direction: column; 
  height: 600px; 
  width: 600px; 
  justify-content: stretch; 
  align-items: stretch; 
} 
#board .row{ 
  display: flex; 
  flex-direction: row; 
  justify-content: stretch; 
  align-items: stretch; 
  flex: 1; 
} 
.square { 
  background-color: red; 
  border: white solid 1px; 
  flex: 1; 
  /* 关键添加:让square成为flex容器,对齐属性才会生效 */
  display: flex;
  justify-content: center; 
  align-items: center; 
  /* 可选:增加鼠标指针样式,提升交互感 */
  cursor: pointer;
} 
#board .row .square:hover{ 
  background-color: yellow; 
} 
.square:hover:before { 
  content: "O"; 
  /* 可选:调整文字样式,让它更显眼 */
  font-size: 4em;
  color: #333;
}

额外小技巧

如果不想用Flex,也可以用传统的居中方式:给.square设置text-align: center,再把它的line-height设为和自身高度一致(不过这种方法在容器高度动态变化时不够灵活)。但Flex的方式更通用,不管容器尺寸怎么变,都能完美居中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:29:12