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

Dav*_*nes 6 javascript reactjs material-ui jss

我在尝试使用 MaterialUI 中的组件实现一些简单的事情时遇到了非常困难的情况Grid。具体来说,我想在一个布局行上将一个项目左对齐,将另一个项目右对齐。

我进行了广泛的搜索,但没有找到任何有效的解决方案。我尝试了很多建议,包括在组件中使用justifyContent和在 JSS 中,以及“推送”内容的技术。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>
Run Code Online (Sandbox Code Playgroud)

MaterialUI JSS 样式:

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

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

您对这个问题有什么建议或解决办法吗?

太感谢了,

戴维斯

Zan*_*ane 14

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

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

const useStyles = makeStyles((theme) => ({
  right: {
    marginLeft: 'auto'
  }
}));
Run Code Online (Sandbox Code Playgroud)
<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> 
Run Code Online (Sandbox Code Playgroud)


Aay*_*rma 8

我使用了一种不同的方法来在右侧列出一个网格项。类似的方法可用于在右侧显示网格项,在左侧显示一个网格项。

<Grid container>
  <Grid item>Left</Grid>                          
  <Grid item xs>                                 
    <Grid container direction="row-reverse">      
      <Grid item>Right</Grid>
    </Grid>
  </Grid>
</Grid>
Run Code Online (Sandbox Code Playgroud)


nic*_*ahi 4

flex我认为这里最好的选择是这样使用:

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    width: '100%'
  },
  rowLayout: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center' // To be vertically aligned
  },
}));
Run Code Online (Sandbox Code Playgroud)

作为第二个选择(对我来说这是最好的选择,因为你正在使用 Material UI 的最完整表达,如果你正在使用它,这是最好的选择。尽可能多地使用该库)你可以这样做:

<Container>
  <Grid container spacing={3}>
    <Grid container direction="row" justify="space-between" alignItems="center">
      // 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>
Run Code Online (Sandbox Code Playgroud)