简体   繁体   English

在material-ui中居中对齐项目

[英]Center align items in material-ui

I am rendering some cards in a container row and need to align them in the center with equal spacing around.我正在容器行中渲染一些卡片,并且需要将它们以相等的间距对齐在中心。 I am using UI library material-ui for the layout.我正在使用 UI 库 material-ui 进行布局。 Even though I have added the justifyContent: center property, the cards have uneven spacing around them.即使我添加了justifyContent: center属性,卡片周围的间距也不均匀。

This is what the current UI looks like:这是当前 UI 的样子:

在此处输入图像描述

Notice the extra space on the right side of the last card.注意最后一张卡片右侧的额外空间。 On inspecting, the spacing scale looks like this:检查时,间距比例如下所示:

Here is the code so far:这是到目前为止的代码:

const Home = ({ cards }) => {
  return (
    <Container maxWidth="xl">
      <Grid
        container
        justifyContent="center"
        spacing={3}
        my={8}
      >
        {cards.map((card) => {
          return (
            <Grid item xs={12} sm={6} md={3}>
              <Card sx={{ maxWidth: 300 }}>
                <CardActionArea>
                  <CardMedia
                    component="img"
                    height="140"
                    image="../../bg2.png"
                    alt="green iguana"
                  />
                  <CardContent>
                    <Typography gutterBottom variant="h5" component="div">
                      {card.title}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {card.description}
                    </Typography>
                  </CardContent>
                </CardActionArea>
                <CardActions>
                  <Button size="small" color="primary">
                    View More
                  </Button>
                </CardActions>
              </Card>
            </Grid>
          );
        })}
      </Grid>
    </Container>
  );
};

If I remove the container wrapper <Container maxWidth="xl"> , then the UI looks like this:如果我删除容器包装<Container maxWidth="xl"> ,那么 UI 看起来像这样:

在此处输入图像描述

I am not a very good hand at MUI, If anyone can help to rectify the issue and achieve desired results, will be really helpful.我不是 MUI 的好手,如果有人可以帮助纠正问题并达到预期的效果,那将非常有帮助。

Here is a live demo that spaces your cards out evenly. 是一个现场演示,可将您的卡片均匀分布。 Use justifyContent = "space-evenly" in conjunction with alignItems = "center" .justifyContent = "space-evenly" evenly" 与alignItems = "center"结合使用。

编辑 MediaCard 材料演示(分叉)

在此处输入图像描述

import * as React from "react";
import Card from "@mui/material/Card";
import CardActions from "@mui/material/CardActions";
import CardContent from "@mui/material/CardContent";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Grid from "@mui/material/Grid";

export default function MediaCard() {
  const cards = [1, 2, 3];
  return (
    <Grid
      container
      direction="row"
      justifyContent="space-evenly"
      alignItems="center"
    >
      {cards.map(() => (
        <Card sx={{ maxWidth: 345 }}>
          <CardContent>
            <Typography gutterBottom variant="h5" component="div">
              Lizard
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Lizards are a widespread group of squamate reptiles, with over
              6,000 species, ranging across all continents except Antarctica
            </Typography>
          </CardContent>
          <CardActions>
            <Button size="small">Share</Button>
            <Button size="small">Learn More</Button>
          </CardActions>
        </Card>
      ))}
    </Grid>
  );
}

You can accomplish this with a little hacky.您可以通过一些 hacky 来完成此操作。

There are some others questions like yours as you can see here and here with some alternatives to accomplish what you want.您可以在此处此处看到其他一些与您类似的问题,并提供一些替代方案来完成您想要的。

Based on the answers to the above questions, I've created a codesample using this hacky with a custom hook that returns the dimensions of the window.根据对上述问题的回答,我使用这个带有自定义钩子的hacky创建了一个代码示例,该钩子返回窗口的尺寸。

So, let`s go to the code:那么,让我们看一下代码:


const cards = [1, 2, 3, 4, 5];

// const related to the card maxWidth
const maxWidth = 300;

// const related to the total Cards Width - based on how cards the screen contains.
const totalwidth = maxWidth * cards.length;

// get the actual width of the screen
const { width } = useWindowDimensions();

// Check if the width screen is smaller than the total count of all cards width
// and if yes, we do the hacky mentioned above.
const screenSmallerThanAllCardsWidth = width < totalwidth + 20;// just added +20 to garantee

The hacky - add extra (n - 1) filler divs hacky - 添加额外(n - 1) filler divs

let divsHacky= [];

  if (screenSmallerThanAllCardsWidth)
    for (var i = 0; i < cards.length - 1; i++) {
      divsHacky.push(
        <Box
          key={i}
          sx={{
            width: maxWidth,
            height: 0
          }}
        />
      );
    }

The component render:组件渲染:

<Grid container direction="row" justifyContent="space-around">
      {cards.map((item, index) => (
        <Grid item my={1} key={index}>
          <Card sx={{ maxWidth }}>
            <CardContent>
              <Typography gutterBottom variant="h5" component="div">
                Lizard
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Lizards are a widespread group of squamate reptiles, with over
                6,000 species, ranging across all continents except Antarctica
              </Typography>
            </CardContent>
            <CardActions>
              <Button size="small">Share</Button>
              <Button size="small">Learn More</Button>
            </CardActions>
          </Card>
        </Grid>
      ))}
    // Render the divsHacky if exists
      {divsHacky}
    </Grid>

The windowDimensions custom hook: windowDimensions 自定义钩子:

import { useState, useEffect } from "react";

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
}

export default function useWindowDimensions() {
  const [windowDimensions, setWindowDimensions] = useState(
    getWindowDimensions()
  );

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return windowDimensions;
}

You need to:你需要:

  1. Remove spacing and justifyContent props from Grid container.从 Grid 容器中删除spacingjustifyContent道具。
  2. Add spacing (padding) to Grid items, if you want have spacing!如果您想要间距,请将间距(填充)添加到网格项目!
  3. Grid items should have display of flex with justifyContent="center" prop.网格项目应该显示带有justifyContent="center"flex

Here is a sample on Codesandbox . 这是 Codesandbox 上的示例 I just added borders to demonstrate it better.我只是添加了边框以更好地展示它。

I think wrapping each Card in Grid that has justifyContent="center" alignItems="center" will do我认为将每张卡片包装在具有 justifyContent="center" alignItems="center" 的网格中就可以了

<Grid container direction="row">
  {cards.map(() => (
    <Grid xs={4} item justifyContent="center" alignItems="center">
      <Card sx={{ maxWidth: 345 }}>
        <CardContent>
          <Typography gutterBottom variant="h5" component="div">
            Lizard
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Lizards are a widespread group of squamate reptiles, with over 6,000 species, ranging across all
            continents except Antarctica
          </Typography>
        </CardContent>
        <CardActions>
          <Button size="small">Share</Button>
          <Button size="small">Learn More</Button>
        </CardActions>
      </Card>
    </Grid>
  ))}
</Grid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM