Material-UI Typography doesn't center in AppBar

Issue

I’m trying center the text in an AppBar. I’ve tried centering the text in Typography element, using align=”center”, textAlign=”center”, and style={{ align: “center” }}, among others:

class App extends React.Component {
  render() {
    return (
      <div>
        <AppBar>
          <Toolbar>
            <Typography
              variant="h6"
              color="inherit"
              style={{ align: "center" }}
            >
              Header
            </Typography>
          </Toolbar>
        </AppBar>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));

… but is doesn’t work unless I remove the Toolbar. But then I would have to manually change the height of the AppBar, which I’ve also not found a way to do. In addition, every instance I’ve seen of the AppBar uses the Toolbar. All the solutions that I’ve found that could address this are outdated and don’t work (there’s no such thing as a ToolbarGroup anymore).

I’ve also tried using a const styles and exporting the AppBar withStyles():

const styles = {
  root: {
    flexGrow: 1
  },
  typography: {
    align: "center"
  }
};

function Header(props) {
  const { classes } = props;

  return (
    <div className={classes.root}>
      <AppBar>
        <Toolbar>
          <Typography
            variant="h6"
            color="inherit"
            className={classes.typography}
          >
            Header
          </Typography>
        </Toolbar>
      </AppBar>
    </div>
  );
}

Header.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(Header);

but it also doesn’t work. I’m thinking this should be simple, I’m not sure what I’m missing.

Solution

The AppBar component is styled to render its children as flex items.

CSS property like text-align is used for horizontal alignment of children that is displayed different from a flex item e.g. as a table cell, block or inline-block.

Flex items can be centered horizontally using the justify-content or align-self CSS Property or more other ones.

const styles = {
  root: {
    flexGrow: 1,
  },
  appbar: {
    alignItems: 'center',
  }
};

function Header(props) {
  const { classes } = props;

  return (
    <div className={classes.root}>
      <AppBar
        className={classes.appbar}
        color="default"
        position="static"
      >
        <!--...-->
      </AppBar>
    </div>
  );
}

Answered By – Oluwafemi Sule

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.