求助:解决.hero图片移动端裁切及文本居中问题
Hey Anna, let's tackle those two frustrating problems you've been debugging for an hour. Here's how to get your hero section working perfectly across all devices:
1. Fixing Mobile Hero Image Cropping
Your current background-size: auto is causing the image to not scale properly on small screens. We'll adjust the background properties to ensure it fills the viewport while maintaining aspect ratio without excessive cropping:
Updated .hero CSS:
.hero { display: flex; height: 100vh; width: 100%; background: rgba(76, 76, 76, 1); background: url(https://images.pexels.com/photos/7094/wood-coffee-laptop-hero-7094.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940); background-size: cover; /* Scales image to fill container while preserving aspect ratio */ background-repeat: no-repeat; background-position: center center; /* Keeps image focal point centered on all devices */ /* Removed padding-bottom: 20px to prevent overflow beyond viewport */ }
Why this works:
background-size: coverensures the image fills the entire hero container without stretching, even as screen dimensions change.background-position: center centerprioritizes the middle of the image, so key elements (like the laptop in your photo) stay visible instead of getting cropped off on mobile.- Removing
padding-bottomkeeps the hero exactly100vhtall, avoiding unintended vertical scroll.
2. Centering Text Inside the Hero
Your .hero is a flex container, but you haven't added the alignment properties to center its child elements. Let's fix that:
Add these rules to .hero:
.hero { /* ... existing properties ... */ justify-content: center; /* Centers content horizontally */ align-items: center; /* Centers content vertically */ }
Optional: Ensure text inside .text is centered:
.text { text-align: center; color: white; /* Optional: Makes text stand out against the dark image background */ }
Why this works:
- Flexbox's
justify-contentandalign-itemsproperties will perfectly center the.textdiv both horizontally and vertically within the full-height hero. text-align: centerensures the headings themselves are centered inside their container, which is useful if you add longer text later.
Bonus: Clean Up Media Query Nesting
I noticed you have nested media queries (min-width:726px inside min-width:900px) which won't work as intended. Rewrite them separately for clarity:
@media screen and (min-width: 726px) { /* Styles for tablet-sized screens */ } @media screen and (min-width: 900px) { /* Styles for desktop-sized screens */ }
That should resolve both your issues! Let me know if you run into any other snags.
内容的提问来源于stack exchange,提问作者Anna Gibson

