React+Material UI实现菜品名称与价格间的填充点效果
实现菜品名与价格间的点填充效果
你可以通过调整flex布局结构,在名称和价格之间添加一个占满剩余空间的元素,用重复的点填充空白区域,具体修改如下:
修改后的代码
<Grid container spacing={2}> {coffeeMenu.map((item, index) => ( <Grid item xs={6} key={index}> <Link underline='none' sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', px: 5, fontWeight: 'bold', color: '#000', '&:hover': { color: '#D8AE78', cursor: 'pointer', }, }} > <Typography>{item.name}</Typography> {/* 中间填充点的元素 */} <Typography sx={{ flex: 1, overflow: 'hidden', margin: '0 0.5rem', position: 'relative', '&::after': { content: '"........................................................................"', position: 'absolute', whiteSpace: 'nowrap', left: 0, right: 0, lineHeight: '1', } }} /> <Typography>{item.price}đ</Typography> </Link> </Grid> ))} </Grid>
代码说明
- 移除原有的
justifyContent: 'space-between',改为通过flex:1让中间的点元素占满名称和价格之间的剩余空间 - 用伪元素
::after生成足够多的点,通过overflow: hidden裁剪超出部分,保证点刚好填满空白区域 - 设置
margin: '0 0.5rem'给名称、点、价格之间留出适当间距,避免布局过于紧凑 - 伪元素的
lineHeight: '1'保证点与左右文本的垂直对齐一致
如果觉得伪元素的方式不够直观,也可以直接在中间的Typography标签内写入一串点(比如'........................................'),同样设置flex:1和overflow:hidden,效果完全一致。
内容的提问来源于stack exchange,提问作者Kedo
相关产品推荐
相关产品推荐

