user18943198
user18943198

Reputation:

How to center the label in MUI Textfield

I want to center the label and helper text in the middle of the Textfield. I got it working with adding a padding to MuiInputLabel-root. But this is not responsive on other screen sizes (Textfield changes size and the label isnt in the center anymore). I have tried using textAlign: 'center' but it doesnt work.

  1. Currently I have the Textfield with label on the left: Current

  2. I want to center the label and eventually helper Text too: Expected

  3. Currently when focused paddingLeft is set to 0 again: Focused

const StyledTextField = styled(TextField)({
    '& .MuiInputLabel-root': {
        paddingLeft: '85px',
    },
    '& label.Mui-focused': {
        color: '#000000',
        paddingLeft: '0px',
    },
    
     <StyledTextField
                        helperText="Privacy Policy "
                        InputProps={{
                            inputProps: {
                                style: { textAlign: 'center' },
                            },
                        }}
                        margin="normal"
                        fullWidth
                        id="email"
                        label="Email Address"
                        name="email"
                        autoComplete="email"
                        autoFocus
                        sx={{
                            m: 1,
                        }}
                    />

Upvotes: 1

Views: 8398

Answers (1)

Akis
Akis

Reputation: 2252

Here is how I was able to solve your issue (updated code).

const StyledTextField = styled(TextField)({
  "& .MuiInputLabel-root": {
    right: 0,
    textAlign: "center"
  },
  "& .MuiInputLabel-shrink": {
    margin: "0 auto",
    position: "absolute",
    right: "0",
    left: "0",
    top: "-3px",
    width: "150px", // Need to give it a width so the positioning will work
    background: "white" // Add a white background as below we remove the legend that had the background so text is not meshing with the border
    // display: "none" //if you want to hide it completly
  },
  "& .MuiOutlinedInput-root.Mui-focused": {
    "& legend ": {
      display: "none"
    }
  }
});

export default function BasicTextFields() {
  return (
    <StyledTextField
      helperText="Privacy Policy "
      InputProps={{
        inputProps: {
          style: { textAlign: "center" }
        }
      }}
      margin="normal"
      fullWidth
      id="email"
      label="Email Address"
      name="email"
      autoComplete="email"
      autoFocus
    />
  );
}

Here is the UPDATED codesandbox to try it. Let me know what you think.

Upvotes: 3

Related Questions