【问题标题】:How do I vertically align my items in a material-UI Grid row?如何在 Material-UI Grid 行中垂直对齐我的项目?
【发布时间】:2020-08-17 12:08:19
【问题描述】:

我正在使用 Material UI 的 Grid 组件来连续显示三个项目。我想将项目垂直对齐到中心,但我在执行此操作时遇到了令人失望的挑战。显然“justifyContent: 'center'”只是水平居中的项目。我发现了这个

const styles = (theme) => ({
  root: {
    textAlign: "left",
    margin: theme.spacing(2),
    paddingBottom: theme.spacing(1),
    color: theme.color.secondary,
  },
  cardHeader: {
    paddingBottom: theme.spacing(0),
  },
  cardContent: {
    width: "100%",
    paddingBottom: theme.spacing(1),
  },
  rowBody: {
    width: "100%",
    flexWrap: "nowrap",
    alignItems: "center",
    justifyContent: 'center',
  },
...
      <CardContent className={classes.cardContent}>
        <Grid container className={classes.rowBody} spacing={1}>
          <Grid item>
            <img height="20" src={require('../../img/apple.svg')} alt="" />
          </Grid>
          <Grid item>
            {title}
          </Grid>
          <Grid item className={classes.infoIcon}>
            <InfoIcon />
          </Grid>
        </Grid>

产生以下内容。

如何在不水平对齐的情况下垂直对齐我的项目?

【问题讨论】:

    标签: css reactjs grid material-ui vertical-alignment


    【解决方案1】:

    Svg 和 img 元素具有display: inline-block。内联块有一个底部间隙。您只需要将显示更改为阻止。

    我创建了Sandbox 作为示例

    【讨论】:

      【解决方案2】:

      [编辑]:基于 Kiril 的回答(感谢沙盒),这就是我的想法:

      import React from "react";
      import { Grid } from "@material-ui/core";
      import { Error } from "@material-ui/icons";
      
      export default function App() {
        return (
          <Grid container spacing="1" alignItems="center">
            <img
              src="https://yt3.ggpht.com/a/AATXAJxK3dHVZIVCtxjYZ7mp77wBbCs9fw4zU46V_Q=s288-c-k-c0xffffffff-no-rj-mo"
              alt="no-src"
              height="20px"
            />
            <span style={{ padding: 5 }}>no title supplied</span>
            <Error />
          </Grid>
        );
      }
      
      

      你不能把你的三个元素放在同一个网格中吗?这样做会更容易,而且您的实际代码也可以工作。

      如果没有,您的网格可能已对齐,但内容未对齐,因为它不是 flex 容器的直接子级。尝试将display: table-cell; verticalAlignment:center 添加到您的网格项目(或将其内容包装在宽度和高度为 100% 的 div 中)

      【讨论】:

      • 我很乐意按照您的建议去做。你有它如何工作的例子吗?
      猜你喜欢
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 2022-01-11
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多