将一个组件垂直居中,并将appbar置于屏幕材质UI的顶部

I am new to material UI, and am having problems centering a component (horizontally and vertically) whilst including an AppBar for navigation at the top my screen. I understand that there are solutions like this, using a grid, however, this will align ALL items, including my AppBar in the middle, which I do not want. Any help would be greatly appreciated, as I have been pulling out my hair trying to work this out (I'm usually a backend dev).

评论
svero
svero

A common way to do this is to position your AppBar sticky as a sibling of an element containing the "main" section of your app.

A standard approach would be the following (I will use Grid since you are using material-ui):

<Grid id="whole-app" style={{ position: "relative", height: "90vh" }}>
  <Grid
    id="appbar"
    style={{ position: "sticky", top: 0, left: 0, right: 0 }}
  >
    Some AppBar content
  </Grid>
  <Grid
    id="main"
    container
    justify="center"
    alignItems="center"
    style={{ height: "inherit" }}
  >
    <div>Main section</div>
  </Grid>
</Grid>

You can check it here.

You can see the rationale: We have a container element that has a height and is positioned (#whole-app) and has two children, the sticky AppBar and the main content area. The main section container has display: flex (the container prop), a height so you can see the vertical alignment and the corresponding props for centering its children.

Your code sandbox was buggy because align is not a valid Grid prop and you don't need the spacing prop.

As a side note, I suggest you check tailwindcss, which I think is easier for beginners.

点赞
评论
wsint
wsint

您可以将添加display flex到父组件的任何元素居中,如下所示:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
点赞
评论