如何排列页面中的React组件使其居中垂直堆叠展示
解决方法
你当前的问题根源是:只给单个输入栏组件设置了内部内容居中的规则,没有为批量生成的所有组件添加统一的外层控制容器,单个固定宽度的块级元素默认会靠左排列。按以下步骤修改即可:
- 修改批量生成组件的
IngredientsInput代码,为所有输入栏添加外层容器
export const IngredientsInput = (props) => { let inputBars = []; for (let i = 0; i < props.numIngredients; i++) { inputBars.push( <IngredientsInputBar newServings={props.newServings} originalServings={props.originalServings} /> ); } return <div className="ingredients-input-container">{inputBars}</div>; }
- 新增外层容器的CSS样式
/* 全局基础重置(可选,避免默认边距影响) */ html, body { margin: 0; padding: 0; height: 100%; } .ingredients-input-container { /* 子元素垂直堆叠 */ display: flex; flex-direction: column; /* 子元素水平居中 */ align-items: center; /* 可选:调整组件之间的间距 */ gap: 12px; /* 可选:如果需要整个组件组在页面垂直居中,添加以下两行 */ /* min-height: 100vh; justify-content: center; */ } /* 你原有代码不需要修改,justify-content: center已经实现了输入栏内部内容居中 */ .ingredients-input-bar { display: flex; background-color: rgb(71, 79, 105); justify-content: center; width: 400px; }
如果不想加外层容器,也可以直接给.ingredients-input-bar添加margin: 0 auto 12px auto规则,同样能实现单个组件水平居中,不过添加外层容器的可扩展性更强,后续调整布局更方便。
内容的提问来源于stack exchange,提问作者RaidingGames
相关产品推荐
相关产品推荐

