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