多背景图垂直堆叠布局:实现仅按高度缩放且保持宽高比的问题
Hey there, let's figure out how to get those vertically stacked images filling the screen perfectly while keeping their aspect ratios intact—no stretching, no wonky resizing. Here's a straightforward CSS solution that aligns with your priority of preserving image quality over forcing a fit:
Step 1: HTML Structure
First, wrap each image in a container that'll act as your full-screen viewport section:
<div class="fullscreen-image"> <img src="your-first-image.jpg" alt="Descriptive text for accessibility"> </div> <div class="fullscreen-image"> <img src="your-second-image.jpg" alt="More descriptive text"> </div> <!-- Add as many sections as you need -->
Step 2: CSS Implementation
This code ensures each section fills the entire screen, scales images by height first (as you want), and preserves aspect ratio without stretching. We'll use overflow hiding for any parts of the image that exceed the screen width—this way, you get a full-height, distortion-free image instead of squashing it:
/* Reset default browser styles to avoid unexpected spacing */ * { margin: 0; padding: 0; box-sizing: border-box; } /* Make each image container take up the full viewport */ .fullscreen-image { height: 100vh; /* Matches the height of the user's screen */ width: 100vw; /* Matches the width of the user's screen */ overflow: hidden; /* Hide any image parts that go beyond the container */ } /* Style images to scale correctly */ .fullscreen-image img { height: 100%; /* Force image height to fill the container */ width: auto; /* Let width adjust proportionally to keep aspect ratio */ object-fit: cover; /* Fallback to ensure image covers the container without stretching */ /* Optional: Center the image horizontally so cropping is balanced */ display: block; margin: 0 auto; }
How This Works for Your Target Resolutions
- 1920x1080: If your image is 1920x1080, it’ll fit perfectly. For images with wider aspect ratios (like 21:9), the height will stay at 1080, and the excess width will be cropped evenly from both sides—no stretching, no quality loss.
- 1000x1080: The image height scales to 1080 (filling the screen vertically), and the width adjusts proportionally. If your original image is wider than 1000px (like 1920px), the extra width gets cropped, but the aspect ratio stays 100% intact. No squashing, no distorted images.
Quick Note on Image Quality
To avoid noticeable quality drops, make sure your source images are at least as large as your largest target resolution (1920x1080 or bigger). Using modern formats like WebP can also help maintain quality while keeping file sizes manageable.
内容的提问来源于stack exchange,提问作者Hermansen

