【问题标题】:Vertically center text inside grid element在网格元素内垂直居中文本
【发布时间】:2026-02-05 03:35:02
【问题描述】:

我需要在设置了 minHeigh 属性的网格项内垂直居中文本,here's short codesandbox example of the problem i'm facing、justify、alignItems,似乎不起作用。

  <Grid container className={classes.root}>
    <Grid item xs={12}>
      <Grid
        container
        spacing={16}
        className={classes.demo}
        alignItems={alignItems}
        direction={direction}
        justify={justify}
      >
        {[0, 1, 2].map(value => (
          <Grid
            key={value}
            item
            style={{
              padding: "0 12px",
              minHeight: 48,
              borderStyle: "solid"
            }}
          >
            {`Cell ${value + 2}`}
          </Grid>
        ))}
      </Grid>
    </Grid>

style={{ minHeight: 48 }} 应用于&lt;Grid item /&gt; 网格项的子项未对齐时,justify、alignItems 对其没有任何影响。

【问题讨论】:

  • 请提供有关您的问题的更多详细信息,并将您的相关代码直接添加到您的问题中。这样可以更轻松地为您提供帮助,谢谢!
  • 您能给我们一些您的代码吗?这肯定有助于找到解决方案

标签: javascript css reactjs


【解决方案1】:

您还需要向元素添加另外两个属性。

display: inline-flex;
align-items: center;

如果这是您期望的结果

      <Grid
        container
        spacing={16}
        className={classes.demo}
        alignItems={alignItems}
        direction={direction}
        justify={justify}
      >
        {[0, 1, 2].map(value => (
          <Grid
            key={value}
            item
            style={{
              display: "inline-flex", // <--
              alignItems: "center",   // <--
              padding: "0 12px",
              minHeight: 48,
              borderStyle: "solid"
            }}
          >
            <p>{`Cell ${value + 2}`}</p>
          </Grid>
        ))}
      </Grid>

【讨论】:

    【解决方案2】:

    试试vertical-align: middle,看看是否可行?或者如果盒子是一个固定的高度,你总是可以在它的顶部添加边距。希望对您有所帮助!

    【讨论】:

      【解决方案3】:

      您可以这样做。将文本包装在 div 中并使用 alignItems: https://codesandbox.io/s/8nw8v9yv02

      【讨论】: