实现header覆盖绝对定位hero-img,后续div位于其下方
Hey there, the issue you're facing is a classic one with absolute positioning: elements set to position: absolute get pulled out of the normal document flow, so subsequent elements like .paragraph and .cta don’t account for the hero image’s height and end up sitting underneath it. Here are a few solid solutions to get those elements properly positioned below the hero:
Solution 1: Wrap in a Positioned Parent Container
This is the most reliable approach, as it keeps the hero image contained while preserving its space in the document flow:
Updated HTML:
<div class="hero-wrapper"> <div class='header'></div> <div class='hero-img'></div> </div> <div class='paragraph'></div> <div class='cta'></div>
Adjusted CSS:
.hero-wrapper { position: relative; /* Makes the hero-img position relative to this container */ height: 60vh; /* Matches the hero-img's height */ min-height: 10em; width: 100%; } .hero-img { height: 100%; /* Fills the wrapper's height */ width: 100vw; left: 50%; right: 50%; margin-left: -50vw; margin-right: -50vw; background-size: cover; background-position: center; position: absolute; top: 0; z-index: 0; /* Ensures header sits above it */ } .header { position: relative; /* Needed to set z-index */ z-index: 1; }
The wrapper maintains the hero image’s height in the document flow, so all content after it will naturally fall below.
Solution 2: Add Top Margin to Subsequent Elements
If you don’t want to modify your HTML structure, you can push the first post-hero element down with a margin that matches the hero’s height:
.paragraph { margin-top: 60vh; /* Matches hero-img's height */ min-margin-top: 10em; /* Accounts for the min-height */ }
Note that this is less flexible for responsive designs—you’ll need media queries to adjust the margin if the hero’s height changes across screen sizes.
Solution 3: Use CSS Grid for Clean Layout
For a more modern approach, CSS Grid lets you layer the header and hero while defining clear rows for your content:
No HTML changes needed—just update your CSS:
body { display: grid; grid-template-rows: 60vh auto auto; /* First row = hero height, rest auto-size */ min-row-height: 10em; } .header { grid-row: 1; /* Places header in the first row */ grid-column: 1; z-index: 1; } .hero-img { grid-row: 1; /* Overlaps hero with header in the first row */ grid-column: 1; width: 100vw; left: 50%; right: 50%; margin-left: -50vw; margin-right: -50vw; background-size: cover; background-position: center; } .paragraph { grid-row: 2; /* Second row for paragraph */ } .cta { grid-row: 3; /* Third row for CTA */ }
This keeps your layout organized and is great for responsive setups where you might want to adjust row heights easily.
Pick the solution that fits your project’s needs—Solution 1 is the most backward-compatible, while Solution 3 offers a cleaner, more maintainable modern layout.
内容的提问来源于stack exchange,提问作者Kevin Danton

