为何页面垂直溢出时HTML右侧宽度被撑开?求修复方案
问题:斜线分隔元素导致页面右侧宽度被撑开的修复
问题场景
尝试通过设置border实现两段文本间的斜线分隔,但当body内容溢出页面底部时,页面右侧宽度被莫名撑开,出现水平滚动条。
原代码
CSS代码
* { box-sizing: border-box; margin: 0px; padding: 0px; } html { background-color: green; } body { background-color: red; } body .diagonal { border-top: 10vw solid blue; border-right: 100vw solid purple; }
HTML代码
<html> <body> SECTION 1 <div class="diagonal"></div> Why does the html enlarge the width on the right when the body overflows the bottom of the page? Thanks <br>text <br>text <br>Try by adding some text line and scrool left <br>text <br>text <br>text <br>text <br>text <br>text <br>text </body> </html>
原因分析
问题出在.diagonal的border-right: 100vw设置上:
vw是视口宽度单位,代表浏览器可视区域的全宽- 当body内容溢出产生垂直滚动条时,body的实际可用宽度是「视口宽度 - 滚动条宽度」
- 此时
100vw的右边框宽度会超出body的实际宽度,导致页面被强制撑开,出现水平滚动条
修复方案
方案1:限制body的水平溢出
给body添加overflow-x: hidden,直接隐藏水平方向的溢出内容,避免页面被撑开:
body { background-color: red; overflow-x: hidden; /* 添加这一行 */ }
方案2:匹配body宽度设置斜线
将border-right的单位从vw改为%,并确保斜线元素宽度适配父容器(body):
body .diagonal { border-top: 10vw solid blue; border-right: 100% solid purple; /* 替换100vw为100% */ width: 100%; /* 确保元素宽度匹配父容器 */ }
两种方案都能解决问题,方案2更贴合「斜线仅占据body宽度」的需求,方案1则更简单直接。
内容的提问来源于stack exchange,提问作者Kutch56
相关产品推荐
相关产品推荐

