如何实现主按钮后方左右等宽均分的双色背景布局
问题原因
你当前的实现存在两个核心问题:
.yesIcon的z-index设置为1,.noIcon的z-index为0,层级规则下绿色背景会覆盖金色背景- 用大padding配合负margin的实现方式稳定性差,按钮宽度变化后容易出现错位、覆盖范围不符合预期的问题
最优解决方案
推荐用容器伪元素实现背景分色,无需修改现有JS结构,适配性更强,修改后的CSS代码如下:
.wrapper { display: flex; flex-direction: row; align-items: center; position: relative; } /* 左右分色背景 */ .wrapper::before, .wrapper::after { content: ""; position: absolute; top: 0; bottom: 0; width: 50%; z-index: 0; } .wrapper::before { left: 0; background: limegreen; } .wrapper::after { right: 0; background: gold; } .yesIcon { z-index: 1; margin-right: 20px; /* 可自行调整图标和按钮的间距 */ } .noIcon { z-index: 1; margin-left: 20px; /* 可自行调整图标和按钮的间距 */ } /* 中间按钮层级高于背景 */ .matchesDIVs { position: relative; z-index: 2; }
现有代码快速修复
如果不想调整实现逻辑,直接修改原有CSS即可解决覆盖问题:
.yesIcon { background: limegreen; box-sizing: border-box; padding-top: 80%; padding-bottom: 80%; padding-right: 80%; z-index: 0; /* 统一背景层级 */ margin-right: -50%; position: relative; } .noIcon { background: gold; padding-top: 80%; padding-bottom: 80%; padding-left: 80%; z-index: 0; /* 统一背景层级 */ margin-left: -50%; position: relative; } /* 新增按钮样式,层级高于背景 */ .matchesDIVs { position: relative; z-index: 1; } .wrapper { display: flex; flex-direction: row; align-items: center }
内容的提问来源于stack exchange,提问作者Robot123
相关产品推荐
相关产品推荐

