如何使用 Material UI 网格组件将一个项目左对齐,另一个项目右对齐

新手上路,请多包涵

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

我进行了广泛的搜索,但没有找到任何有效的解决方案。 I’ve tried many suggestions, including the use of justifyContent and alignContent within a Grid component, and within JSS, and the flex: 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 组件,如果可能的话,我希望编写更简洁的代码。

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

太感谢了,

戴维斯

原文由 Davis Jones 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 824
1 个回答

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

灵感来自: How to align flexbox columns left and right?

 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>

原文由 Zane 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题