Search code examples
reactjsmaterial-uiappbar

How to make Appbar content not stretch to sides on larger displays


I would like to center my Appbar content, so it doesn't spread to sides of the screen when on larger displays. There are images of how it looks like vs how I would like it to look.

The thing is that on smaller screens, both the Appbar and page content fits right into the screen, but on larger displays, Appbar content continues to spread, while page content stays centered. So I would like the Appbar to stay fullwidth while its content stays on same place as page content - as you can see in second screen.

My page code:

<Box sx={{ display: "flex" }}>
  <CssBaseline />
  <AppBar
    position="fixed"
    sx={{
      marginTop: "10px",
      width: `100%`,
    }}
  >
    <Toolbar>
      <IconButton
        color="inherit"
        aria-label="open drawer"
        edge="start"
        sx={{ mr: 2, display: { sm: "none" } }}
      >
        <MenuIcon />
      </IconButton>
      <Box
        sx={{
          borderBottom: 1,
          borderColor: "divider",
          mr: 2,
          display: { xs: "none", sm: "block", md: "block" },
        }}
      >
        <Tabs
          aria-label="basic tabs example"
          TabIndicatorProps={{
            style: {
              background: "#ffffff",
            },
          }}
        >
         // MY TABS 
        </Tabs>
      </Box>
      <div className={classes.alignRight}>
        <IconButton
          color="inherit"
          aria-label="open drawer"
          edge="right"
        >
          <LogoutRoundedIcon />
        </IconButton>
      </div>
    </Toolbar>
  </AppBar>
  <Box
    component="nav"
    sx={{ width: { sm: 0 }, flexShrink: { sm: 0 } }}
    aria-label="mailbox folders"
  >
  </Box>
  {/* Page content */}
  <Box
    component="main"
    sx={{
      flexGrow: 1,
      p: 3,
    }}
  >
    // MY CONTENT
  </Box>
</Box>

Changing Appbar position tag to position="static" changes it to desired width, but I want only the content of that width.


Solution

  • <AppBar position="static">
      <Toolbar
        sx={{
          width: "100%",
          maxWidth: 600,
          mx: "auto"
        }}
      >
    
    • Set a maxWidth to restrict the width on large screen
    • Set width to 100% to expand the content width within the maxWidth limit above.
    • Set margin left and right to auto to center the Toolbar itself inside the Appbar

    Live Demo

    Codesandbox Demo