首页 > 解决方案 > 当第一个网格项是固定宽度时,如何在 Material UI 中左右对齐两个网格项?

问题描述

我正在使用 Material UI 并有一个 Grid 容器,其中包含三个 Grid 项目。最左侧的项目应具有 240 像素的固定宽度,并且内容应左对齐。中间的 Grid 项目应该向左对齐,并且可以是任何宽度 - 内容包含一些按钮(我在下面的代码中省略了)并且应该左对齐。右边的 Grid 项目应该是右对齐的,最好是大约 240px 或屏幕的一部分(例如 xs="3")。它必须是移动响应的。这是一张图片:

在此处输入图像描述

我试过使用 justify="flex-end" 和 justify="space-between" 但问题是它弄乱了布局。内容最终堆叠在一起。任何人都可以推荐一个好的方法吗?

import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles(theme => ({
  root: {
    minHeight: 40,
    alignItems: 'center',
    padding: theme.spacing(0, 2),
  },
  fixedWidthContainer: {
    width: '240px',
  },
  titleSpacing: {
    marginRight: theme.spacing(2),
  },
}));

const AdminBar = () => {
  const classes = useStyles();

  return (
    <Grid container className={classes.root}>
      <Grid item className={classes.fixedWidthContainer}>
        <Typography variant="body2">
          Title: MyTitle
        </Typography>
      </Grid>
      <Grid item>
        <Typography
          className={classes.titleSpacing}
          variant="body2"
          component="span"
        >
          Some stuff to go on the left
        </Typography>
      </Grid>
      <Grid item className={classes.fixedWidthContainer}>
        Some stuff to go on the right
      </Grid>
    </Grid>
  );
};

export default AdminBar;

非常感谢,

凯蒂

标签: reactjsflexboxmaterial-ui

解决方案


Grid根据需要为物品提供尺寸配给。喜欢边项目提供xs={3}和中心项目集flex-grow:1

<Grid container className={classes.root}>
  <Grid item xs={3} className={classes.fixedWidthContainer}>
    <Typography variant="body2">Title: MyTitle</Typography>
  </Grid>
  <Grid item style={{ flexGrow: "1" }}>
    <Typography
      className={classes.titleSpacing}
      variant="body2"
      component="span">
      Some stuff to go on the left
    </Typography>
  </Grid>
  <Grid xs={3} item className={classes.fixedWidthContainer}>
    Some stuff to go on the right
  </Grid>
</Grid>

沙盒链接:- https://codesandbox.io/s/xenodochial-flower-ge65z

个人意见:-在这种情况下,最好只使用div它们然后相应地设置它们,因为你在这里有固定宽度的要求。我在沙箱中添加了这个方法


推荐阅读