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

flexDirection属性失效求助:如何用Flexbox实现元素横向排列?

问题根源一眼就能看到啦!

兄弟,你这代码里藏着个“反向操作”的小错误——你设置的flexDirection: 'column'本身就是让元素纵向排列的属性呀!难怪不管怎么调,色块都是竖着排的😂

想要实现横向排列,只需要把外层容器的flexDirection改成'row'就行,另外记得给宽高加上px单位(不然部分浏览器可能不识别无单位的数值),修改后的代码如下:

<div style={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}>
  <div style={{width: '50px', height: '50px', backgroundColor: 'powderblue'}} />
  <div style={{width: '50px', height: '50px', backgroundColor: 'skyblue'}} />
  <div style={{width: '50px', height: '50px', backgroundColor: 'steelblue'}} />
</div>

再给你两个小补充:

  • Flexbox的默认flexDirection就是row,如果没有特殊需求,你甚至可以直接删掉flexDirection这一行,效果完全一样
  • 行内样式的数值尽量带上单位,避免不同浏览器出现解析差异

这样修改后,三个色块就能横向居中排列啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:07:45