How to Achieve Proportional Image and Video Scaling with CSS
This article explains how to maintain correct aspect ratios for images and videos in responsive layouts by setting only one dimension for images and using an intrinsic‑ratio container with padding‑bottom for videos, complete with practical CSS code examples.
Before discussing easy proportional scaling, we first cover how images scale proportionally.
For images, setting only the width or height causes the other dimension to adjust automatically based on the image's intrinsic ratio, for example:
<img src="http://placehold.it/200x150">
<img src="http://placehold.it/400x300">
.demo1{
width: 100px; /* only width set, height becomes 75px */
}
.demo2{
height: 150px; /* only height set, width becomes 200px */
}Because images have an inherent width‑height ratio, setting one value automatically determines the other. But what about videos?
In responsive design, videos are usually required to keep a 16:9 or 4:3 aspect ratio. When the browser width changes, the video width changes, and its height must adjust accordingly to preserve the chosen ratio.
A clever solution—Creating Intrinsic Ratios for Video—provides a container whose height is set to 0 and whose padding-bottom is set to 56.25% (the percentage is based on the container's width, so the padding expands the container height while keeping the aspect ratio). The video is then positioned absolutely to fill the container.
.wrap{
height: 0;
padding-bottom: 56.25%; /* 16:9 */
position: relative;
width: 100%;
}
.wrap .video{
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}Based on this concept, we can extend it to other scenarios. For example, a mobile page may need three full‑screen images where the left and right images have equal width, the first and third images align at the bottom, and the spacing between images is 10 px. Because mobile screen sizes vary, fixed widths are unsuitable.
See the container aspect‑ratio demo for detailed implementation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
