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

如何让div宽度适配space-around布局下两个子元素的间距范围?

解决锦标赛布局中水平线宽度适配问题

可以通过调整DOM结构并利用flex布局特性,优雅实现水平线仅占两个垂直线之间宽度的效果:

  1. 调整HTML结构:将水平线元素移到verticalLineWrapper容器内,放在两个垂直线之间
  2. 修改CSS样式:移除水平线的width: 100%,添加flex-grow: 1让它自动填充垂直线间的剩余空间

修改后的完整代码

CSS

.duel {
    display: flex;
    flex-direction: column;
}

.verticalLine {
    background-color: black;
    width: 5px;
    height: 50px;
}

.center {
    align-self: center;
}

.horizontalLine {
    background-color: black;
    height: 5px;
    flex-grow: 1; /* 自动填充垂直线之间的剩余空间 */
    margin: auto 0; /* 垂直方向居中对齐 */
}

.verticalLineWrapper {
    display: flex;
    align-items: center; /* 确保容器内元素垂直居中 */
    width: 100%;
}

.opponent {
    width: 100px;
}

.opponents { /* 修正原拼写错误:opponets → opponents */
    display: flex;
    justify-content: space-around;
    gap: 4px;
}

HTML

<div class="duel">
    <img class="opponent center" src="https://picsum.photos/100?asdf=1" draggable="false" />
    <div class="verticalLine center"></div>
    <div class="verticalLineWrapper">
        <div class="verticalLine"></div>
        <div class="horizontalLine"></div>
        <div class="verticalLine"></div>
    </div>
    <div class="opponents"> <!-- 修正拼写错误 -->
        <img class="opponent" src="https://picsum.photos/100?asdf=2" draggable="false" />
        <img class="opponent" src="https://picsum.photos/100?asdf=3" draggable="false" />
    </div>
</div>

实现原理

  • 原结构中水平线作为独立元素,width:100%会继承父容器的全宽,导致超出垂直线范围
  • 将水平线放入verticalLineWrapper后,flex布局会把三个元素(左垂直线、水平线、右垂直线)横向排列,flex-grow:1让水平线自动填充两个垂直线之间的所有空隙,精准匹配需求宽度
  • align-items: center确保垂直线和水平线垂直对齐,视觉上更协调统一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 23:23:36