You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MUI实现:用虚线连接Avatar组件

实现MUI Stack中Avatar的虚线连接效果

可以通过伪元素+定位的方式实现虚线连接,同时优化布局避免float带来的问题,具体实现如下:

修改后的代码

import { Stack, Avatar, Box } from '@mui/material';

export default function ConnectedAvatars() {
  return (
    <Stack 
      sx={{ 
        position: 'relative',
        // 生成垂直虚线的伪元素
        '&::before': {
          content: '""',
          position: 'absolute',
          left: '23px', // 计算方式:margin(8px) + Avatar半宽(15px)
          top: '15px', // Avatar半高,让线从第一个Avatar中心开始
          height: 'calc(100% - 30px)', // 总高度减去两个Avatar半高,线到最后一个Avatar中心结束
          borderLeft: '2px dashed #999', // 虚线样式,可按需调整颜色、粗细
          zIndex: 0
        }
      }}
    >
      <Box sx={{ display: 'flex', alignItems: 'center' }}>
        <Avatar 
          sx={{ 
            width: 30, 
            height: 30, 
            marginRight: 1, 
            backgroundColor: '#c00500',
            position: 'relative',
            zIndex: 1 // 让Avatar覆盖虚线,形成连接效果
          }} 
          variant="square"
        >C</Avatar>
        Today
      </Box>
      <Box sx={{ display: 'flex', alignItems: 'center' }}>
        <Avatar 
          sx={{ 
            width: 30, 
            height: 30, 
            marginRight: 1, 
            backgroundColor: '#05C000',
            position: 'relative',
            zIndex: 1
          }} 
          variant="square"
        >V</Avatar>
        Yesterday
      </Box>
      <Box sx={{ display: 'flex', alignItems: 'center' }}>
        <Avatar 
          sx={{ 
            width: 30, 
            height: 30, 
            marginRight: 1, 
            backgroundColor: '#c00500',
            position: 'relative',
            zIndex: 1
          }} 
          variant="square"
        >C</Avatar>
        Yesterday
      </Box>
    </Stack>
  );
}

关键实现细节

  • 替换float为flex布局:用display: flex和alignItems: center让Avatar与文本垂直居中,布局更稳定。
  • 利用Stack的伪元素生成虚线:通过绝对定位将虚线放在Avatar的中心位置,确保连接每个Avatar的中间点。
  • 层级控制:给Avatar设置zIndex:1,让Avatar覆盖虚线,营造出虚线连接Avatar的视觉效果。
  • 可自定义调整:修改borderLeft的颜色、粗细,或调整left/top的值来适配不同尺寸的Avatar。

内容的提问来源于stack exchange,提问作者Black

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 04:18:18