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

如何实现::before伪元素高度自适应,适配手风琴组件连接线需求

解决方案

方案1:子项分布式绘制连接线(推荐,适配任意动态子项数量)

放弃在父容器绘制整根竖线,改为每个子项各自绘制所属的竖线段,可自动适配子项数量、子项内容高度不定的场景:

// 承载所有子手风琴的父容器
.sub-accordion-container {
  position: relative;
  margin-left: 2rem;
  padding: 0;
}

// 每个子手风琴项
.accordion-item {
  position: relative;
  padding-left: 1.5rem; // 留出横线+圆点的展示空间
  // 绘制子项所属的竖线段
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 1px;
    background: #003d76;
    height: 100%;
  }
  // 最后一个子项的竖线仅绘制到圆点位置即截止
  &:last-child::before {
    height: 12px; // 此处替换为你UI中圆点中心到子项顶部的实际距离
  }
  // 绘制横向连接线+圆点
  &::after {
    content: '';
    position: absolute;
    left: 0;
    top: 8px; // 此处替换为圆点中心到子项顶部的实际距离,和上方高度值适配
    width: 12px; // 横线长度可根据UI调整
    height: 1px;
    background: #003d76;
    // 圆点样式
    &::before {
      content: '';
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: #003d76;
    }
  }
}

方案2:保留父容器绘制整根竖线的实现

如果不想修改原有结构,可通过动态计算竖线高度实现需求:

.sub-accordion-container {
  position: relative;
  margin-left: 2rem;
  padding: 0 0 12px 0; // 底部padding值等于圆点中心到最后一个子项底部的实际距离
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    background: #003d76;
    width: 1px;
    // 竖线高度 = 容器总高度 - 底部padding值,刚好截止在最后一个圆点位置
    height: calc(100% - 12px);
  }
}

如果子项有展开收起的动效,现代浏览器会自动处理重绘逻辑,无需额外兼容。

内容的提问来源于stack exchange,提问作者Sai Yerni Akhil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:45:01