首页 > 解决方案 > 如何使用 Material UI Grid 组件将一个项目左对齐和另一个右对齐

问题描述

我很难尝试使用GridMaterialUI 中的组件来实现一些简单的事情。具体来说,我想在一个布局行上将一个项目左对齐,另一个项目右对齐。

我进行了广泛搜索,但没有找到任何有效的解决方案。我尝试了很多建议,包括在组件内和在 JSS内的使用,justifyContent以及“推送”内容的技术。alignContentGridflex: 1

相关代码片段

试图把<Typography>元素放在左边,<FormGroup>右边:

<Container>
  <Grid container spacing={3}>
    <Grid className={classes.rowLayout}>
      // Goal is to align this to the LEFT
      <Grid item xs={6}>
        <Typography variant="h6" gutterBottom>Some Text</Typography>
      </Grid>
      // Goal is to align this to the RIGHT
      <Grid item xs={3}>
        <FormGroup>
          // Simple `Switch` button goes here
        </FormGroup>
      </Grid>
    </Grid>
  </Grid>
</Container>

MaterialUI JSS 样式:

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    width: '100%'
  },
  rowLayout: {
    display: 'flex',
    alignItems: 'baseline'
  },
}));

我还发现,一般来说,这需要使用许多Grid组件,如果可能的话,我很想编写更简洁的代码。

您对此问题有任何提示或解决方法吗?

太感谢了,

戴维斯

标签: javascriptreactjsmaterial-uijss

解决方案


我现在正在使用它,它可以很好地将一个对齐到最左边,一个对齐到最右边。

灵感来自:如何左右对齐 flexbox 列?

const useStyles = makeStyles((theme) => ({
  right: {
    marginLeft: 'auto'
  }
}));
<Grid container alignItems="center">
  <Grid>
    <Typography variant="h4" component="h4">Left</Typography>
  </Grid>
  <Grid className={classes.right}>
    <Button variant="contained" color="primary">Right</Button>
  </Grid>
</Grid> 

推荐阅读