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

如何实现div元素之间连接线的自适应效果,无需频繁编写媒体查询

问题根因

你当前的实现用了固定宽度的连接线、基于item自身宽度的固定偏移值,父容器用justify-content: space-between时两个item的间距会随容器宽度动态变化,固定参数自然会错位。

自适应解决方案

方案1:固定间距自适应(推荐,实现最简洁)

给父容器用gap属性控制item间距,通过CSS变量统一管理间距值,连接线宽度直接调用变量即可适配,无需媒体查询:

&__snake {
    display: flex;
    justify-content: flex-start;
    /* 统一设置间距,修改时只改这里即可 */
    gap: 60px;
    --snake-gap: 60px;
    --item-width: 185px;
}

&__snake-item {
    height: var(--item-width);
    width: var(--item-width);
    border-radius: 40px 0px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;

    &:not(:last-child)::after {
        content: '';
        position: absolute;
        /* 宽度直接用全局定义的间距值,自动适配 */
        width: var(--snake-gap);
        height: 50%;
        /* 定位在当前item的右侧边缘 */
        left: 100%;
        top: 50%;
        transform: translateY(-50%);
        border-top: 2px solid violet;
        border-right: 2px solid violet;
    }
}

方案2:两端对齐自适应

如果需要item两端对齐填充整行,可通过总容器宽度、item总宽度计算动态间距,只需要在父容器上声明item总数量变量即可:

&__snake {
    display: flex;
    justify-content: space-between;
    --item-count: 4; /* 替换为你实际的item数量 */
    --item-width: 185px;
    /* 自动计算两个item之间的动态间距 */
    --snake-gap: calc( (100% - var(--item-width) * var(--item-count)) / (var(--item-count) - 1) );
}

&__snake-item {
    height: var(--item-width);
    width: var(--item-width);
    border-radius: 40px 0px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;

    &:not(:last-child)::after {
        content: '';
        position: absolute;
        width: var(--snake-gap);
        height: 50%;
        left: 100%;
        top: 50%;
        transform: translateY(-50%);
        border-top: 2px solid violet;
        border-right: 2px solid violet;
    }
}

小屏幕折行适配补充

如果需要适配小屏幕item折行的场景,只需要加一个断点修改伪元素样式即可,无需逐个写媒体查询:

@media (max-width: 768px) {
    &__snake {
        flex-direction: column;
        gap: 40px;
        --snake-gap: 40px;
    }
    &__snake-item:not(:last-child)::after {
        width: 2px;
        /* 垂直连接线高度等于行间距 */
        height: var(--snake-gap);
        left: 50%;
        top: 100%;
        transform: translateX(-50%);
        /* 水平连接线改为垂直 */
        border-top: none;
        border-right: none;
        border-left: 2px solid violet;
        border-bottom: 2px solid violet;
    }
}

内容的提问来源于stack exchange,提问作者Влад Лисовский

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:54:00