使用Next.js+TypeScript开发404页面时,Tailwind的w-screen与h-screen导致响应式失效及滚动条异常问题排查
Hey there! I totally get staring at code for too long and missing the obvious—let's break down why those double scrollbars are popping up and fix them.
What's Causing the Issue?
Your suspicion about h-screen/w-screen and layout is spot on! Here's the breakdown:
- Browser Default Styles: Most browsers add a tiny default margin to the
<body>element. When you useh-screen(100vh) andw-screen(100vw) on your divs, this default margin pushes the elements just enough outside the viewport, triggering scrollbars. - Redundant Viewport Sizing: Your absolute-positioned background div uses
h-screen w-screen, but combining that with absolute positioning can create overflow if not handled right. Plus, having two full-height divs (even layered) can compound the issue if the default body styles aren't reset.
Step-by-Step Fixes
1. Reset Global Default Styles
First, wipe out browser defaults that cause unexpected spacing. If you're using Tailwind, add this to your globals.css file:
@tailwind base; @tailwind components; @tailwind utilities; /* Reset default browser margins/padding */ html, body { margin: 0; padding: 0; overflow-x: hidden; /* Prevent unwanted horizontal scroll */ }
2. Optimize the Background Layer
Replace h-screen w-screen with inset-0 on your absolute-positioned background div. inset-0 is Tailwind's shorthand for top: 0; right: 0; bottom: 0; left: 0;, which guarantees the div fills the entire viewport without overflow:
<div className="bg-gray-900 inset-0 flex justify-center items-center absolute z-0"> <svg className="p-6 lg:p-48 fill-current text-gray-300 max-w-full" viewBox="0 0 445 202" xmlns="http://www.w3.org/2000/svg" fill="none" stroke="currentColor"> {/* SVG path remains the same */} </svg> </div>
We also added max-w-full to the SVG to ensure it never spills outside its container on smaller screens.
3. Adjust the Content Layer
For your relative content layer, swap h-screen w-screen with min-h-screen and remove w-screen:
<div className="min-h-screen flex justify-center items-center relative z-10"> {/* Your content remains the same */} </div>
min-h-screenensures the layer takes up at least the full viewport height (perfect for centering content) without forcing a fixed height that might overflow.- Removing
w-screenlets the div naturally take up the full width of its parent (the body) without risking horizontal overflow from scrollbar spacing.
Final Notes
With these changes, your layered layout stays intact, and those annoying scrollbars should disappear. The key was fixing the default browser styles and using more reliable positioning/sizing classes for your layered elements.
内容的提问来源于stack exchange,提问作者Pranta

