两个全屏div上下相对布局时出现多余滚动条问题求助
Hey there, let’s break down why your two vertically stacked full-screen divs are causing unwanted scrollbars and width overflow—here are the most common fixes to get things working right:
1. Reset Default Browser Styles First
Browsers add default margin/padding to html and body elements, which is often the hidden culprit here. Single divs might not trigger obvious issues, but two stacked ones amplify this extra space. Add this to your CSS to wipe those defaults:
html, body { margin: 0; padding: 0; overflow-x: hidden; /* Stop horizontal overflow dead in its tracks */ }
2. Use box-sizing: border-box for Your Divs
If your divs have padding or borders, the default content-box box model will make their total width exceed 100vw. Switching to border-box ensures padding/borders are included in your defined width/height:
.full-screen-div { position: relative; width: 100vw; height: 100vh; box-sizing: border-box; /* Critical for preventing overflow */ }
3. Tame Unintended Margins & Child Overflow
- Margin collapse between the two divs could add extra vertical space, or child elements inside the divs might be spilling outside their bounds. Add
overflow: hiddento your divs to contain any rogue child content:
.full-screen-div { overflow: hidden; /* Hide any content that spills outside the div */ }
Full Working Example
Here’s a complete code snippet that ties all these fixes together:
<!DOCTYPE html> <html> <head> <style> html, body { margin: 0; padding: 0; overflow-x: hidden; } .full-screen-div { position: relative; width: 100vw; height: 100vh; box-sizing: border-box; overflow: hidden; } .top-div { background: #f4f4f4; } .bottom-div { background: #e8e8e8; } </style> </head> <body> <div class="full-screen-div top-div"></div> <div class="full-screen-div bottom-div"></div> </body> </html>
This setup will give you two perfectly stacked full-screen divs with no extra scrollbars or width overflow—you’ll only get the vertical scrollbar you expect for navigating between the two sections.
内容的提问来源于stack exchange,提问作者JohnsonD

