innoxius
innoxius

Reputation: 127

How to align horizontally the label of TextField in React Material-UI at the center?

I'd like to align horizontally the label at the center of this TextField:

import React from "react";
import { withStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";       
        
        export default function BasicTextField() {
          return (
              <TextField
                id="standard-basic"
                label="Standard"/>
          );
        }

So far I was able to align the label at the right:

import React from "react";
import { withStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";       

const StyledTextField = withStyles({
          root: {
            "& label": {
              transformOrigin: "top right",
                right: "0",
                left: "auto" 
            }
          }
        })(TextField);
        
        export default function BasicTextField() {
          return (
              <StyledTextField
                id="standard-basic"
                label="Standard"/>
          );
        }

Is there a way to align the label horizontally at the center?

Upvotes: 1

Views: 7102

Answers (2)

turchak
turchak

Reputation: 450

Try this

root: {
        "& label": {
          width: "100%",
          textAlign: "center",
          transformOrigin: "center",
            "&.Mui-focused": {
              transformOrigin: "center"
            }
         }
      }

Upvotes: 2

Guilherme Campos
Guilherme Campos

Reputation: 53

You can use a Box component to center your label like this:

<Box display="flex" justifyContent="center">
    <StyledTextField id="standard-basic" label="Standard"/>
</Box>

Or a Grid component:

<Grid container
  direction="row"
  justify="center"
  alignItems="center"
>
  <StyledTextField id="standard-basic" label="Standard"/>
</Grid>

Upvotes: 0

Related Questions