cssreactjsmaterial-uijss

Fix TextField Alignment in React


I need to fix a simple problem in the styling of my React App. I wonder why the CVC TextField in my react app doesn't align to the Card Number.

Pls check this codesandbox link

CLICK HERE

<div style={{ display: 'flex' }}>
  <TextField
    variant="outlined"
    label="Expiration Month"
    name="expiryMonth"
    type="text"
    value={values.expiryMonth}
    onChange={handleChange}
    onBlur={handleBlur}
    helperText={touched.expiryMonth ? errors.expiryMonth : ''}
    error={touched.expiryMonth && Boolean(errors.expiryMonth)}
    fullWidth
    className={classes.margin}
    style={{ flex: 1 }}
  />

  <TextField
    variant="outlined"
    label="Expiration Year"
    name="expiryYear"
    type="text"
    value={values.expiryYear}
    onChange={handleChange}
    onBlur={handleBlur}
    helperText={touched.expiryYear ? errors.expiryYear : ''}
    error={touched.expiryYear && Boolean(errors.expiryYear)}
    fullWidth
    className={classes.margin}
    style={{ flex: 1 }}
  />

  <TextField
    variant="outlined"
    label="CVC"
    name="cvc"
    type="number"
    value={values.cvc}
    onChange={handleChange}
    onBlur={handleBlur}
    helperText={touched.cvc ? errors.cvc : ''}
    error={touched.cvc && Boolean(errors.cvc)}
    fullWidth
    className={classes.margin}
    style={{ flex: 1 }}
  />
</div>;

Solution

  • By default, each TextField has a margin of 8px due to which, the flex row of three text field(month, year and CVV) has 8 px gap with their children.

    there are multiple fixes, the first one is

    <div style={{ display: "flex", width="calc(100% + 16px)" }}>
    

    This will force the row to take 16px more than 100% because we have 8px margin on TextField on both side so it will help us to overcome 8px margin on both side another solution would be to add a negative margin of 16px on right side

    <div style={{ display: "flex",  margin: "-16px" }}>
    

    I would recommend you to use Grid component from MUI because it will also help you to achieve responsive design, below is the code with Grid as a container, to make it responsive you will need to wrap each child component TextField in Grid item component

    <Grid
              style={{ display: "flex", margin: 0 }}
              container
              direction="row"
              justify="center"
              alignItems="center"
              spacing={2}
            >
    

    Sand-box-project-1
    Sand-box-project-2