材质UI中的相同高度的卡片

时间:2019-04-24 07:11:06

标签: material-ui

尝试拥有3张水平的卡片,但高度相同并且要响应。

卡A |卡B |卡C

4 个答案:

答案 0 :(得分:6)

我认为这是一种更简单的方法:

https://github.com/creativetimofficial/ct-material-dashboard-pro-react/issues/45#issuecomment-442885173

import React from "react"
import { Card, CardBody, CardFooter } from "components"

import withStyles from "@material-ui/core/styles/withStyles"

const styles = {
fullHeightCard: {
    height: "100%",
    },
}

const Item = (props) => {
    const {classes} = props

    // 1-5 paragraphs to create card height variance
    let paragraphs = 1 + Math.floor(Math.random() * Math.floor(5))

    return (
        <Card className={classes.fullHeightCard}>
            <CardBody>
                {Array(paragraphs).fill().map((_,i) => (
                    <p>{i+1}</p>
                ))}
            </CardBody>
            <CardFooter>
            {'Footer content'}
            </CardFooter>
        </Card>
    )
}

export default withStyles(styles)(Item)

答案 1 :(得分:2)

您必须将以下属性添加到您的 Card

.MuiCard-root{
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

它会在 CardContentCardActions 之间添加必要的空格

这里回答了同样的问题:How to make Material-UI CardActions always stick to the bottom of parent

答案 2 :(得分:1)

您可以使用Grid组件来实现此目的:

<Grid container alignItems="stretch">

  <Grid item component={Card} xs>
    <CardContent>
       // Card A content
    </CardContent>
    <CardActions>
      // Card A actions
    </CardActions>
  </Grid>

  <Grid item component={Card} xs>
    <CardContent>
      // Card B content
    </CardContent>
    <CardActions>
      // Card B actions
    </CardActions>
  </Grid>

  <Grid item component={Card} xs>
    <CardContent>
      // Card B content
    </CardContent>
    <CardActions>
      // Card B actions
    </CardActions>
  </Grid>
</Grid>

alignItems="stretch"(实际上不需要指定,因为默认为Stretch),当flex方向为row时,它具有拉伸每个项目的高度的效果(这也是默认方向)。您可以查看此答案以获取更多详细信息:https://stackoverflow.com/a/46956430/253693

每个xs上的Grid item属性利用auto-layout的优势,指示每张卡均等地共享可用宽度。

您还可以解决一些清理问题,即使用withStyles HOC将一个类应用于固定间距的每个Card组件,并确保CardActions保留在卡片的底部,无论CardContent的高度:

const styles = {
  card: {
    // Provide some spacing between cards
    margin: 16,

    // Use flex layout with column direction for components in the card
    // (CardContent and CardActions)
    display: "flex",
    flexDirection: "column",

    // Justify the content so that CardContent will always be at the top of the card,
    // and CardActions will be at the bottom
    justifyContent: "space-between"
  }
};

然后您将这些样式应用于每张卡,如下所示:

<Grid item component={Card} xs className={classes.card}>

这是一个将所有内容整合在一起的有效示例:https://codesandbox.io/embed/r9y95vr5n

答案 3 :(得分:0)

按照上面的答案中的建议覆盖with的呈现组件会弄乱间距(spacing的{​​{1}}道具停止工作)。请查看下面有关如何实现卡的垂直对齐而又不会产生不良副作用的说明。

<Grid container />上设置display: 'flex'应该足以对齐所有<Grid item />元素的高度。

不过,要获得垂直拉伸<Card /><CardContent>的效果,请在<CardActions>元素上同时设置display: 'flex', justifyContent: 'space-between', flexDirection: 'column'

<Card />