【发布时间】:2021-04-25 04:05:14
【问题描述】:
1。当前外观
我有一个包含 4 个网格项的 Material UI 网格容器。每个 Grid 项中都有一个 Typography 组件,其中包含一个标题和一个带有一些内容的 Card,如下所示:
2。理想的外观
我希望卡片填充网格项目的剩余高度并且不超过它。这是我想要的输出:
3。不良外观(卡片高度 = 100%)
我已经尝试将卡片的高度设置为 100%,但这意味着每张卡片都采用其父级(网格项目)的高度,并且父级的高度 = 排版 + 卡片(而不是剩余空间减去Typography),所以结果是 Card 超出了父 Grid 项的高度,如下所示:
解决这个问题的最佳方法是什么?我正在使用 Material UI 的 Grid 来简化断点并与我的项目的其余部分保持一致,因此理想情况下,解决方案将使用这种方法。
代码如下:
import React from 'react';
const useStyles = makeStyles(theme => ({
// stretch: { height: '100%' }, // Un-commenting this results in undesirable appearance 3 (see image 3 above)
outline: { border: '1px solid red' },
}));
const Sections= () => {
const classes = useStyles();
return (
<Grid container spacing={3} justify="space-between" alignItems="stretch" className={classes.outline}>
<Grid item xl={2} lg={2} md={6} xs={12} className={classes.outline}>
<Typography className={classes.outline}>Big title 1</Typography>
<Card className={classes.stretch}><CardContent>Lots and lots and lots and lots and lots and lots of content</CardContent></Card>
</Grid>
<Grid item xl={4} lg={4} md={6} xs={12} className={classes.outline}>
<Typography className={classes.outline}>Big title 2</Typography>
<Card className={classes.stretch}><CardContent>Not much content</CardContent></Card>
</Grid>
<Grid item xl={3} lg={3} md={6} xs={12} className={classes.outline}>
<Typography className={classes.outline}>Big title 3</Typography>
<Card className={classes.stretch}><CardContent>Not much content</CardContent></Card>
</Grid>
<Grid item xl={3} lg={3} md={6} xs={12} className={classes.outline}>
<Typography className={classes.outline}>Big title 4</Typography>
<Card className={classes.stretch}><CardContent>Not much content</CardContent></Card>
</Grid>
</Grid>
);
};
export default Sections;
非常感谢,
凯蒂
【问题讨论】:
-
我认为您遗漏了部分代码。例如每张卡片上方的附加“大标题”。您能否更新代码 sn-p 以包含它?谢谢
-
我创建了一个stackblitz 实例,我相信它会达到您想要的结果。有趣的是,我取消了您的样式的注释,并且它似乎正在工作。有一些问题是您的
<Grid />标记的顺序不正确,所以这可能是您的样式以前不起作用的原因。 -
谢谢查尔斯 - 我已经修改了代码,希望它现在看起来正确吗?正如您所建议的,我也意识到在错误的位置有一个结束标记 。除此之外,我可以看到您的代码正在运行,但我不明白其中的区别?与我自己的代码相比,我不得不大量简化此处显示的代码,所以我试图找出差异!你介意解释一下吗?非常感谢!
-
实际上 - 我可以看到我担心该解决方案不起作用。如果您将边框应用到网格,那么您会看到它类似于上面的图像 3。 Cards 超出了父 Grid 的高度。非常感谢您的帮助!
-
凯蒂,我在我的第一个解决方案中意识到了这个问题并更新了它。我希望它有帮助!感谢您提供的图片显示了预期的结果。
标签: javascript css reactjs material-ui