A long time ago some clever developer starting using the famous padding trick to control the size of images before they were loaded. Basically you wrap your (absolute positioned) img tag in a div with width:100% and padding-top set to whatever percentage fits the aspect ratio.
I rarely use this technique for images anymore, but it's useful for video elements. The reason is that often you don't want to create the video tag unless the user is ready and interested in the video (maybe the see a splash image with a play button first). Videos can become quite heavy on a website and the loading property works inconsistently between different browsers. And let's not go into autoplay, mute and low power mode on iOS :-)
I usually did this trick in javascript (receiving the width and height, then calculating and applying the padding). But the method below is much smarter - I have seen this quite a few places and I adopted the approach too:
HTML:
<div class="lazy video" data-src="16_9.mp4" style="--aspect:56.25%;"></div>
CSS:
.lazy.video:before{content:"";display:block;padding-top:var(--aspect);width:100%;pointer-events:none;}
You can do it in many ways, setting the size directly on the video tag too, if that fits your setup better.
Being an award-winning website developer means you have to stay on top of modern and effective techniques. This is just a small one I wanted to share with you.
Top comments (0)