Hacker News new | ask | show | jobs
by superfad 1836 days ago
The browser doesn’t know the size at which the image will be rendered on the page until it has downloaded and parsed all the relevant CSS and JavaScript files. Shortly after the browser downloads the HTML, it requests CSS and JavaScript. But before the CSS and JavaScript is done loading, the browser starts downloading images. The only thing that the browser does know is the size of the viewport. If we give sizes based on screen width then the browser will know which image to use. The width doesn’t have to be expressed as a viewport width unit though. It can be any length including absolute and relative length. You can even use CSS calc() to do things like auto-calculate margins dynamically.

For your example I believe it would be done like so:

<img src="cat-200.jpg" alt="cat" srcset="cat-200.jpg 200w, cat-400.jpg 400w, cat-800.jpg 800w" sizes="5em">

This page explains responsive images further: https://cloudfour.com/thinks/responsive-images-101-part-5-si...