CSS Flexbox 如何实现带分隔符的两个元素均匀间距
问题解决方案
问题根源
你遇到的间距不均问题来自两个核心原因:
#listSectionContainer的gap只会在flex子项(左列表容器、分隔线、右列表容器)的外边缘之间加固定间距,左右两个.dropdownSection等宽,但内部内容都默认左对齐,右容器的内容从自身左边缘开始排版,自然离分隔线更近- 你给
.dropdownLinks加的position: absolute虽然避免了hover挤压,但也让列表脱离了文档流,无法继承容器的对齐属性,放大了间距不均的问题
优化修改方案
核心调整点
- 替换hover过渡效果实现方式:用
transform: translateX()代替padding-left变化,元素占位空间不会改变,无需使用绝对定位就能避免布局偏移 - 统一左右列表的对齐规则:左列表内容左对齐,右列表内容右对齐,保证分隔线两侧到列表内容的距离完全相等
- 移除冗余的绝对定位相关代码,让列表回到正常文档流,布局更稳定
完整修改后代码
CSS代码
#container { width: 600px; padding-top: 20px; } #listSectionContainer { display: flex; padding: 30px; gap: 30px; } .dropdownSection { display: flex; flex-direction: column; justify-content: flex-start; height: 210px; flex: 1; } /* 给右侧列表单独加右对齐规则 */ .dropdownSection:last-of-type { align-items: flex-end; } .sectionSeparator { width: 3px; background-color: rgba(178, 178, 178, 0.35); border-radius: 8px; flex-shrink: 0; /* 避免分隔线被挤压变形 */ } .dropdownSectionTitle { display: flex; align-items: flex-start; color: #8B8792; font-size: 20px; } .dropdownSectionTitle i { height: 20px; width: 20px; background: grey; margin-right: 10px; } /* 右侧标题调整图标边距 */ .dropdownSection:last-of-type .dropdownSectionTitle i { margin-right: 0; margin-left: 10px; } .dropdownSectionTitle p { font-weight: bold; margin: 0; } .dropdownLinks { display: flex; flex-direction: column; margin-top: 25px; font-size: 18px; padding-left: 28px; } /* 右侧列表调整内边距 */ .dropdownSection:last-of-type .dropdownLinks { padding-left: 0; padding-right: 28px; align-items: flex-end; } .dropdownLinks a:not(:last-of-type) { margin-bottom: 10px; } .dropdownLinks a:link { color: #939393; text-decoration: none; transition: all 0.2s linear; -webkit-transition: all 0.2s linear; -moz-transition: all 0.2s linear; display: inline-block; /* 保证transform生效 */ } .dropdownLinks a:visited { color: #939393; text-decoration: none; } .dropdownLinks a:hover { color: #7B69FE; transform: translateX(5px); /* 替换padding-left,不改变占位空间 */ text-decoration: none; } /* 右侧链接hover方向相反 */ .dropdownSection:last-of-type .dropdownLinks a:hover { transform: translateX(-5px); } .dropdownLinks a:active { color: #939393; text-decoration: none; }
HTML代码无需修改,直接沿用原代码即可
内容的提问来源于stack exchange,提问作者Erdss4
相关产品推荐
相关产品推荐

