简体   繁体   中英

Align Material UI Grid Items of different length

I currently have a material ui grid system that looks like the following:

<>
      <Typography gutterBottom variant='h6'>
        Add New User{' '}
      </Typography>
      <Grid container spacing={3} alignItems='center' justify='center'>
        <Grid item>
          <Typography variant='body2'>Full name</Typography>
        </Grid>
        <Grid item>
          <TextField
            style={{ width: 400 }}
            fullWidth
            margin='dense'
            id='outlined-basic'
            label='Full name'
            variant='outlined'
          />
        </Grid>
      </Grid>
      <Grid container spacing={3} alignItems='center' justify='center'>
        <Grid item>
          <Typography variant='body2'>Email</Typography>
        </Grid>
        <Grid item>
          <TextField
            style={{ width: 400 }}
            fullWidth
            margin='dense'
            id='outlined-basic'
            label='Email'
            variant='outlined'
          />
        </Grid>
      </Grid>
</>

I am noticing that because email and full name are different lengths, the grid items do not align in the way I would like them to. They currently look like the following:

在此处输入图像描述

I would like the grid to look like the following:

在此处输入图像描述

Is there a way to align the grid items like the bottom picture without needing to add a fixed width? that seems to be the only solution I have found but I feel like I'm missing something regarding the grid system.

attached is a code sandbox https://codesandbox.io/s/affectionate-bhabha-ur9nm?file=/src/App.js for debugging

I've added xs={9} for text-field and xs={3} for the label with style={{ textAlign: 'right' }} (not familiar with material-ui so don't know if there's a better way to apply this).

This is the result: https://codesandbox.io/s/hungry-euclid-n7y8f

you just need to add xs sm lg to your Grid component to take advantage of Auto layout . accoording to the doc:

The Auto-layout makes the items equitably share the available space.

after applying this change, your items will be aligned properly. you can also check the corrected version here in the sandbox .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM