【发布时间】:2021-03-18 05:48:44
【问题描述】:
我正在尝试使用应该具有相同高度(包括图像)的卡片来创建响应式网格布局。我正在使用 React 和 Material-UI。
我现在折腾了好几个小时,却找不到解决办法。 “弹性”部分对我来说似乎超级不直观。请帮忙。
这是一个非常小而简单的代码:
const useStyles = makeStyles((theme: Theme) =>
createStyles({
cardGrid: {
flexGrow: 1,
paddingTop: 16,
},
card: {
flex: 1,
height: '100%',
backgroundColor: 'red',
},
cardActionArea: {
flex: 1,
height: '100%',
backgroundColor: 'green',
},
cardMedia: {
height: '0',
paddingTop: '56.25%', // 16:9
},
cardContent: {
flex: 1,
backgroundColor: blue[600],
},
cardContentTitle: {
flex: 1,
backgroundColor: blue[400],
},
cardContentRating: {
backgroundColor: blue[300],
},
cardContentDistance: {
backgroundColor: blue[200],
}
}),
);
// ...
<Container className={classes.cardGrid} maxWidth="xl">
<Grid
container
direction="row"
justify="space-evenly"
alignItems="stretch"
spacing={2}
>
{
dataList.map(data => (
<Grid item
key={`GridItem-${data.id}`} xs={12} sm={6} md={4} lg={2} xl={1}
>
<Card className={classes.card}
onClick={handleCardClick}
key={`OverviewItem-${data.id}`}
>
<CardActionArea className={classes.cardActionArea}>
{
data.previewURL &&
<CardMedia
className={classes.cardMedia}
image={data.previewURL}
title={data.title}
/>
}
<CardContent className={classes.cardContent}>
<Typography gutterBottom variant="h5" className={classes.cardContentTitle}>
{data.title}
</Typography>
<Typography className={classes.cardContentRating}>
Some text
</Typography>
<Typography className={classes.cardContentDistance}>
Some other text
</Typography>
</CardContent>
</CardActionArea>
</Card>
</Grid>
))
}
</Grid>
</Container>
我想要达到的目标:
- 图片应位于每张卡片的顶部
- “一些文本”和“一些其他文本”应该移到底部
似乎我必须在下树时多次写入“flex:1”和“height:'100%'”,并且在某些时候它会像以下屏幕截图一样完全中断:
上面的代码 sn-p 看起来像这样:
简单地将网格项的子项扩展到其最大高度并仍然能够按照我的需要对齐它们有什么魔力。
例如整个卡片应延伸到网格项的区域,图像下方的标题部分应展开以将图像移动到顶部,将“一些文本”和“一些其他文本”移动到底部。
感谢任何提示/想法!
我能够在没有卡片和图像的情况下实现我想要的。但是让树变大并因此嵌套更深,破坏了一切,我不明白为什么。
这是简单的 sn-p 和结果:
<Container className={classes.cardGrid} maxWidth="xl">
<Grid
container
direction="row"
justify="space-evenly"
alignItems="stretch"
spacing={2}
>
{
toiletOverviews.map(data => (
<Grid item
key={`GridItem-${data.id}`} xs={12} sm={6} md={4} lg={2} xl={1}
>
<Box
display="flex"
flexDirection="column"
style={{height: '100%', backgroundColor: 'purple'}}
>
<Typography
variant="h5"
style={{flex:1, backgroundColor: blue[800]}}
>
{data.title}
</Typography>
<Typography
style={{backgroundColor: blue[600]}}
>
Some text
</Typography>
<Typography
style={{backgroundColor: blue[400]}}
>
Some other text
</Typography>
</Box>
</Grid>
))
}
</Grid>
</Container>
【问题讨论】:
标签: css datagridview flexbox material-ui responsive