繁体   English   中英

在material-ui中居中对齐项目

[英]Center align items in material-ui

我正在容器行中渲染一些卡片,并且需要将它们以相等的间距对齐在中心。 我正在使用 UI 库 material-ui 进行布局。 即使我添加了justifyContent: center属性,卡片周围的间距也不均匀。

这是当前 UI 的样子:

在此处输入图像描述

注意最后一张卡片右侧的额外空间。 检查时,间距比例如下所示:

这是到目前为止的代码:

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>
  );
};

如果我删除容器包装<Container maxWidth="xl"> ,那么 UI 看起来像这样:

在此处输入图像描述

我不是 MUI 的好手,如果有人可以帮助纠正问题并达到预期的效果,那将非常有帮助。

是一个现场演示,可将您的卡片均匀分布。 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>
  );
}

您可以通过一些 hacky 来完成此操作。

您可以在此处此处看到其他一些与您类似的问题,并提供一些替代方案来完成您想要的。

根据对上述问题的回答,我使用这个带有自定义钩子的hacky创建了一个代码示例,该钩子返回窗口的尺寸。

那么,让我们看一下代码:


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

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
          }}
        />
      );
    }

组件渲染:

<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>

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;
}

你需要:

  1. 从 Grid 容器中删除spacingjustifyContent道具。
  2. 如果您想要间距,请将间距(填充)添加到网格项目!
  3. 网格项目应该显示带有justifyContent="center"flex

这是 Codesandbox 上的示例 我只是添加了边框以更好地展示它。

我认为将每张卡片包装在具有 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