【问题标题】:How do I align two Grid items left and one right in Material UI when the first Grid item is a fixed width?当第一个 Grid 项目是固定宽度时,如何在 Material UI 中左右对齐两个 Grid 项目?
【发布时间】:2021-04-11 05:30:11
【问题描述】:

我正在使用 Material UI 并且有一个 Grid 容器,其中包含三个 Grid 项目。最左侧的项目应具有 240 像素的固定宽度,并且内容应左对齐。中间的 Grid 项目应该向左对齐并且可以是任何宽度 - 内容包含一些按钮(我在下面的代码中省略了)并且应该左对齐。右边的 Grid 项目应该是右对齐的,最好是大约 240 像素或屏幕的一部分(例如 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;

非常感谢,

凯蒂

【问题讨论】:

    标签: reactjs flexbox material-ui


    【解决方案1】:

    根据需要为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,然后在这种情况下相应地设置它们的样式,因为您在这里有固定宽度的要求。我已经在沙箱中添加了这个方法

    【讨论】:

    • 我认为您可以在第二个 Grid 项目上使用 xs={true}。
    • 是的..我不知道! :)
    • 太棒了!太感谢了!这解决了我的问题,尽管我不得不从第一个 Grid 中删除 xs={3} ,因为它覆盖了我的固定宽度。我按照dongnhan的建议使用了xs =“true”。这一切都很好!非常感谢您为我节省了更多时间! :)
    • 很高兴。 :) 对于第一个网格问题,给它最大宽度也可以解决问题:
    猜你喜欢
    • 2020-07-06
    • 1970-01-01
    • 2020-08-17
    • 2020-05-21
    • 2021-10-25
    • 2021-09-12
    • 2017-07-18
    • 2021-05-24
    • 2021-04-19
    相关资源
    最近更新 更多