MUI卡片组件中价格文本对齐异常问题求助
解决MUI卡片中价格始终对齐左下角的问题
要让价格始终固定在卡片左下角,核心是利用flex布局让CardContent的内容垂直分布,把描述区域撑满剩余空间,从而将价格推到底部。修改代码如下:
import Card from '@mui/material/Card'; import CardContent from '@mui/material/CardContent'; import CardMedia from '@mui/material/CardMedia'; import Typography from '@mui/material/Typography'; const ItemCard = (props) => { return ( <div> <Card sx={{ maxWidth: 345, boxShadow: '0 2px 8px rgba(0, 0, 0, 0.25)', height: '350px' }} > <CardMedia component='img' height='200' image={props.img} alt='icon' /> {/* 修改CardContent的布局为flex垂直排列,并占满剩余高度 */} <CardContent sx={{ display: 'flex', flexDirection: 'column', height: '100%' }}> <Typography gutterBottom variant='h5' component='div'> {props.name} </Typography> {/* 给描述添加flexGrow:1,让它占据剩余空间 */} <Typography variant='body2' color='text.secondary' sx={{ flexGrow: 1 }}> {props.description} </Typography> {/* 价格自动靠底,同时保持左对齐 */} <Typography sx={{ marginTop: 'auto', textAlign: 'left' }}>TK. {props.price}</Typography> </CardContent> </Card> </div> ); }; export default ItemCard;
关键修改点:
- 给
CardContent添加display: flex、flexDirection: 'column'和height: '100%',让内部元素垂直排列且填满卡片剩余高度 - 给描述文本的
Typography设置flexGrow: 1,使其占据卡片内容区的剩余空间,把价格元素挤到底部 - 给价格的
Typography加marginTop: 'auto',确保无论描述行数多少,价格都固定在底部,textAlign: 'left'保证左对齐
内容的提问来源于stack exchange,提问作者Tato
相关产品推荐
相关产品推荐

