为何将id为here的橙色上层盒子height从100px改为100%后消失?
height: 100% Hey there! Let's break down exactly why your div with id here vanishes when you switch its height from 100px to 100%—it all comes down to how CSS calculates percentage-based heights.
The Core Issue: Percentage Height Needs a Height Context
CSS doesn't treat height: 100% the same way it treats fixed values like 100px. When you use a percentage for height, the browser looks to the parent element to get a reference height. If the parent doesn't have an explicitly defined height (using a fixed unit like px, rem, or vh), the browser can't calculate what "100%" means.
Here's what's happening in your case:
- Your parent element (likely
<body>or another container) probably doesn't have a set height. By default, block elements like<body>only take up as much height as their content requires. - If the parent's height is 0 (because it has no content), your div's
height: 100%will also compute to 0—making it invisible.
Quick Fixes to Bring Your Orange Box Back
1. Make It Fill the Entire Viewport
If you want the div to take up the full height of the browser window, you need to set a height context on the root elements first:
html, body { height: 100%; margin: 0; /* Remove default browser margin to avoid gaps/scrollbars */ } #here { height: 100%; background-color: orange; }
This forces <html> and <body> to take up 100% of the viewport height, giving your div a valid height context.
2. Make It Fill a Specific Parent Container
If the div is inside another container (not the body), set an explicit height on that parent:
.parent-container { height: 400px; /* Or any fixed value that fits your layout */ } #here { height: 100%; background-color: orange; }
3. Use vh Instead (Simpler for Viewport Height)
If you just want the div to match the viewport height without worrying about parent elements, use the vh (viewport height) unit instead of a percentage:
#here { height: 100vh; /* 100% of the viewport's height */ background-color: orange; }
100vh directly refers to the full height of the browser window, no parent height required.
Bonus: Flexbox/Grid Alternative
If you're using modern layout methods like Flexbox, you can make the div fill the parent without relying on percentage heights:
.parent-container { display: flex; min-height: 100vh; /* Or fixed height */ } #here { flex: 1; /* Makes the div take all available space in the flex parent */ background-color: orange; }
内容的提问来源于stack exchange,提问作者user3182532

