That can be handy if we need to combine different aspects of responsive images for the same image element, like screen width and pixel density. We can add a srcset attribute to our existing image.įor more complex definitions, we could wrap a picture element around our image and add multiple source elements each with its own srcset attribute. Now let's tell our browser to use the smaller version if the screen size is not larger than 750 (CSS) pixels. Scaling our image down to that size and saving it as a high quality JPEG file (with JPEG quality set to 80), the new image file only takes up 90 kilobytes, and the image still looks good.Īnd if you're not too ambitious, so does the 70 kB file after further image processing on codepen's asset server:Īdding Source Sets and Sizes to our Image Elements If our mobile screen is 326 CSS pixels wide, at a resolution of 2 device pixels per CSS pixel, we need an image of 750 x 536 pixels to fill our screen. This is responsive in a visual way, but even on a small old mobile phone, browsers will still load the same large image file, half a megabyte of data, only to display a shrunk version of the same image on a tiny screen.Ī much smaller Image File that still looks good We must specify the image source (the URL to the image file) and the original image dimensions (width and height).Įnter fullscreen mode Exit fullscreen mode We will use an image element to show this photograph on our website. As a high resolution photography with a lot of details, the file size is 557.7 kB, which is roughly half a megabyte. Let's start an put one image in an image element, for example this photography of a landscape, 2048 pixels wide, and 1536 pixels high. The image-set() function allows an author to ignore most of these issues, simply providing multiple resolutions of an image and letting the user agent decide which is most appropriate in a given situation. In a typical use case, we provide different image versions and add our recommendation for appropriate screen sizes, but it's up to the browser to decide which image to load: What are source sets and how to use them? This feature has been requested for years, but it did not get the same hype as other, newer, CSS features like parent selectors or container queries.įirst, let's make sure we understand source sets. The image-set property allows us to do the same for background images in CSS. We can use them in different ways to offer browsers alternative versions of the same image to match screen size, pixel density, or network speed. Source sets can help us to make websites load faster.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |