Horizontally centering tabs in Material-UI AppBar with ReactJS
Asked Answered
I

3

5

I'm building a React App with Material-UI and can't figure out how to center the 3 tabs within the blue AppBar. Currently, they are all left-aligned, as such:

https://i.imgur.com/MjQIuBl.png (can't embed images yet, my apologies)

Here is my code:

<div>
  {/* Tabs */}
  <AppBar position="static" color="primary" style={{ position: 'fixed' }}>
    <Tabs
      fullWidth={true}
      value={this.state.value}
      onChange={this.handleChange}
      indicatorColor="secondary"
    >
      <Tab label="Passenger" icon={Icons.seatIcon} component={Link} to="/passenger" />
      <Tab label="Driver" icon={Icons.driverIcon} component={Link} to="/driver" />
      <Tab label="Settings" icon={Icons.settingsIcon} component={Link} to="/settings" />
    </Tabs>
  </AppBar>
</div>

I've experimented with a lot of different CSS properties from similar questions but haven't gotten close. Thanks for your help!

Induction answered 5/3, 2018 at 0:4 Comment(0)
V
20

Try adding "centered" to the Tabs components, like this:

    <div>
  {/* Tabs */}
  <AppBar position="static" color="primary" style={{ position: 'fixed' }}>
    <Tabs
      fullWidth={true}
      value={this.state.value}
      onChange={this.handleChange}
      indicatorColor="secondary"
      centered
    >
      <Tab label="Passenger" icon={Icons.seatIcon} component={Link} to="/passenger" />
      <Tab label="Driver" icon={Icons.driverIcon} component={Link} to="/driver" />
      <Tab label="Settings" icon={Icons.settingsIcon} component={Link} to="/settings" />
    </Tabs>
  </AppBar>
</div>
Vivacious answered 5/3, 2018 at 0:15 Comment(3)
That did it! So what's the difference between centered and something like align-content: center?Induction
@ZachBrown align-content is used to control flexbox. centered is a prop for the Tabs component which applies certain styles defined in Material UI to get the tabs to be centeredVivacious
If fullWidth={true} does not work try variant="fullWidth"; It was for my caseShirlyshiroma
P
2

If the centered property is not working for you, you may try the CSS API (tested with Material-UI 3.7.0). This also gives you a bit more control if you desire:

import { Tabs, withStyles } from '@material-ui/core';

export const CenteredTabs = withStyles({
  flexContainer: {
    justifyContent: 'center',
    alignItems: 'center',
  },
})(Tabs);
Peeling answered 27/12, 2018 at 15:39 Comment(1)
This snippet is outdated. Material-UI is now available in version 4.8 and a lot has changed since Dec 2018Peeling
S
1

This may solve your problem in newer versions of MUI:

<Tabs
     sx={{ margin: "auto" }}
>
Sind answered 4/10, 2022 at 12:6 Comment(1)
Adding margin: 'auto', to my sx prop worked perfectly thank you I had tried the with flexbox and it just wasn't working.Earthling

© 2022 - 2024 — McMap. All rights reserved.