如何用CSS和HTML实现无间距斜向分隔的双色并排盒子?
实现等宽无间距并排双色盒子+斜向分隔线的问题
我尝试用CSS和HTML创建两个等宽、无间距的并排盒子,分别设置不同颜色,且中间带有一条斜向分隔线。原本以为实现起来很简单,但多次尝试都没成功。

我曾试过以下代码,但只能得到中间带黑色斜线的双色盒子,没达到预期效果:
<!DOCTYPE html> <html lang="en"> <head> <style> .container { display: flex; width: 100%; height: 200px; overflow: hidden; } .box { width: 50%; position: relative; } .box1 { background-color: red; } .box2 { background-color: blue; } .divider { width: 200%; height: 200%; position: absolute; background: linear-gradient(135deg, transparent 49.5%, black 49.5%, black 50.5%, transparent 50.5%); top: -100%; left: -100%; } </style> </head> <body> <div class="container"> <div class="box box1"> <div class="divider"></div> </div> <div class="box box2"> <div class="divider"></div> </div> </div> </body> </html>
问题分析
原代码的核心问题是给两个盒子都添加了divider元素,导致两条斜线重叠错位;同时divider的定位和旋转角度设置有误,无法精准落在两个盒子的中间位置。
解决方案1:使用容器伪元素实现分隔线
这种方法只需要一个伪元素,结构更清晰:
<!DOCTYPE html> <html lang="zh-CN"> <head> <style> .container { display: flex; width: 100%; height: 200px; overflow: hidden; position: relative; /* 为伪元素提供定位上下文 */ } .box { width: 50%; height: 100%; } .box1 { background-color: red; } .box2 { background-color: blue; } /* 用容器的伪元素生成斜向分隔线 */ .container::before { content: ''; position: absolute; top: 0; left: 50%; width: 200%; height: 200%; transform: translateX(-50%) rotate(-45deg); background: linear-gradient(to right, transparent 49.5%, black 49.5%, black 50.5%, transparent 50.5%); pointer-events: none; /* 不干扰盒子内的交互操作 */ } </style> </head> <body> <div class="container"> <div class="box box1"></div> <div class="box box2"></div> </div> </body> </html>
解决方案2:纯背景渐变实现(无额外元素)
如果不需要独立的盒子元素承载内容,还可以直接用容器的多重背景实现,结构更简洁:
<!DOCTYPE html> <html lang="zh-CN"> <head> <style> .container { width: 100%; height: 200px; /* 三层背景叠加:左侧红、右侧蓝、中间斜线 */ background: red 0 0 / 50% 100% no-repeat, blue 100% 0 / 50% 100% no-repeat, linear-gradient(-45deg, transparent 49.5%, black 49.5%, black 50.5%, transparent 50.5%) 50% 0 / 200% 200%; } </style> </head> <body> <div class="container"></div> </body> </html>
内容的提问来源于stack exchange,提问作者Saif Tehami
相关产品推荐
相关产品推荐

