HTML Responsive Image Guide: Quick View of Code Snippets
This guide mainly explains the HTML syntax (and a small amount of CSS) of responsive images. Responsive image syntax is designed to provide an image from multiple options based on rules and environments. There are two forms of responsive pictures, which are used for different purposes:
If your only goal is...
Improve performance
Then you need...
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174381805452081.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="HTML Responsive Images Guide">
Here we make the default value ( src
) a "low resolution" (1×) copy of the picture. Using the smallest/fastest resources by default is usually a wise choice. We also offer a 2x version. If the browser knows it is on a higher pixel density display (part 2x), it will use that image.
<img src="/static/imghwm/default1.png" data-src="baby-lowres.jpg" class="lazy" alt="Baby wearing yellow headband smiling." srcset=" baby-high-1.jpg 1.5x, baby-high-2.jpg 2x, baby-high-3.jpg 3x, baby-high-4.jpg 4x, baby-high-5.jpg 100x ">
You can add as many pixel density variants as you want.
While this is cool and useful, the x-descriptor only accounts for a small part of the use of responsive images. Why? They allow browsers to adjust only one content: display pixel density. However, many times, our responsive images are in a responsive layout, and the layout size of the image will shrink and stretch as the viewport changes. In these cases, the browser needs to make decisions based on two items: the pixel density of the screen and the layout size of the picture. This is where the w
descriptor and sizes
attribute come in, we will introduce it in the next section.
Using srcset/w sizes
This is a good thing. This accounts for approximately 85% of the responsive image usage on the network. We are still providing multiple copies of the same image and letting the browser choose the most appropriate copy. However, instead of using pixel density (x) to label them, we use the w descriptor to label their resource width. So if baby-s.jpg
is 300×450, we mark it as 300w.
Using srcset
with a width (w) descriptor like this means it needs to be paired with the sizes
property so that the browser knows how much space the image will be displayed. Without this information, the browser will not be able to make an informed choice.
Create accurate sizes attributes
Creating the sizes
property can be tricky. sizes
property describes the width of the image to be displayed in the layout of your specific website , which means it is closely related to your CSS. The width of the image rendering depends on the layout, not just the viewport!
Let's look at a fairly simple layout with three breakpoints. Here is a demonstration video: (The video link should be inserted here, the original text is missing)
Breakpoints are expressed in CSS using media queries:
body { margin: 2rem; font: 500 125% system-ui, sans-serif; } .page-wrap { display: grid; gap: 1rem; grid-template-columns: 1fr 200px; grid-template-areas: "header header" "main aside" "footer footer"; } @media (max-width: 700px) { .page-wrap { grid-template-columns: 100%; grid-template-areas: "header" "main" "aside" "footer"; } } @media (max-width: 500px) { body { margin: 0; } }
The size of the picture is different at each breakpoint. Here is a breakdown of all parts that affect the layout width of the picture at the maximum breakpoint (when the viewport width is greater than 700 pixels):
- At maximum size: there is an explicit spacing of 9rem, so the width of the picture is
calc(100vw - 9rem - 200px)
. If the column uses fr units instead of 200px, we'll be a little trouble here. - At medium size: the sidebar is placed underneath, so there is less spacing to consider. Nevertheless, we can still use
calc(100vw - 6rem)
to calculate margins and padding. - At minimum size: body margins are removed, so
calc(100vw - 2rem)
is enough.
call! To be honest, I find it a little hard to think about and I made a lot of mistakes in creating this. Finally, I got this:
<img ...="" sizes=" (max-width: 500px) calc(100vw - 2rem), (max-width: 700px) calc(100vw - 6rem), calc(100vw - 9rem - 200px) ">
A sizes
property that provides the browser with the width of the image under all three breakpoints and takes into account the layout grid and all surrounding gaps, margins, and padding that affect the width of the image.
etc! Rumble! ??? This is still wrong. I don't understand why, because to me it looks like it's 100% describing what's going on in the CSS layout. But it is wrong, because Martin Auswöger's RespImageLint says. Running the tool on the isolated demo reported no problem, except that sizes
property is wrong for some viewport sizes and should be:
<img ...="" sizes=" (min-width: 2420px) 2000px, (min-width: 720px) calc(94.76vw - 274px), (min-width: 520px) calc(100vw - 96px), calc(100vw - 32px) ">
I don't know how this is calculated, it's totally impossible to maintain manually, but it's accurate. Martin's tool programmatically resizes the page multiple times and writes out a sizes
property that describes the actual width of the image observed under various viewport sizes. It's math done by computers, so it's correct. So if you want a super precise sizes
property, I recommend putting the wrong property first, running this tool, and copying the correct property.
To get a deeper look at all of this, check out Eric Portis' w
descriptor and sizes
: Behind the Scenes.
More relaxed in sizes
Another option is to use sizes
of the Horseshoe and Grenade Method™ (or, in other words, close to count). This is highly recommended.
For example, sizes="96vw"
means: "This image will be large on the page - almost full width - but there will always be a little padding on the edges, so it is not complete." Or sizes="(min-width: 1000px) 33vw, 96vw"
means: "This image uses a three-column layout on the large screen, otherwise it will be close to full width." In terms of practicality, this may be a reasonable solution.
You may find that some auto-responsive image solutions don't know your layout and therefore make guesses - for example sizes="(max-width: 1000px) 100vw, 1000px"
. It's just saying, "Hey, we don't know much about this layout, but we're going to give it a try, the worst case scenario is that the image is full width, let's hope it never renders over 1000 pixels".
Abstract sizes
I believe you can imagine that not only is it easy to get sizes
wrong, but it will also become wrong over time as the website layout changes. You'd better use a template language or a content filter to abstract it so that you can change the values of all images on your website more easily.
I'm actually talking about setting sizes
value in one variable at a time and then many different things on the website<img alt="HTML Responsive Images Guide" >
Use this variable in the element. Native HTML does not provide this functionality, but it does it in any backend language; for example, PHP constants, Rails configuration variables, React context APIs for global state variables, or variables in template languages such as Liquid can be used to abstract sizes
.
<?php // in global scope $my_sizes = ""; ?> <img alt="" sizes="<?php echo $my_sizes; ?>" src="" srcset="">
"Browser Selection"
Now that we have the sizes
property, the browser knows the size (or close to that size) of the image and can do its magic . That is, it can do some mathematical operations that take into account the pixel density of the screen and the size of the image to render, and then choose the most suitable image.
At first, math was quite simple. Suppose you are about to display a picture of 40vw in a viewport with a width of 1200 pixels on a 2x pixel density screen. The perfect picture width should be 960 pixels, so the browser will look for the closest picture. The browser will always calculate its preferred target size based on viewport and pixel density conditions and what you know from sizes
property and compare that target with what it has in srcset
for selection. However, it can be a little strange how the browser makes the selection.
If the browser chooses to do so, it may include more content into this equation. For example, it can take into account the user's current network speed, or whether the user has enabled some kind of "data saving" preference. I'm not sure if any browsers actually do this, but they can do it freely if they want, because that's how the specification is written. Some browsers sometimes choose to extract from cache. If the math operations indicate that they should use a 300 pixel image, but they already have a 600 pixel image in the local cache, they will use that image directly. clever. Leaving space for such things is an advantage of srcset
/ sizes
syntax. This is also why you always use the same image's different sizes in srcset
: you can't know which image you will select. This is the browser choice .
This is very strange. Don't the browser already know these things?
You might be thinking, "Well, why do I have to tell the browser how big the image will render, don't it know?" Well, it knows, but only after it downloads your HTML and CSS and lays out everything. sizes
attribute is related to speed. It provides enough information for the browser to see your<img alt="HTML Responsive Images Guide" >
Make informed choices when tagging.
<img data-sizes="auto" data-srcset=" responsive-image1.jpg 300w, responsive-image2.jpg 600w, responsive-image3.jpg 900w">
Now you might be thinking, "But what about the picture that is delayed loading?" (that is, when requesting the picture that is delayed loading, the layout has been completed and the browser already knows the rendering size of the picture). OK, great idea! Alexander Farkas' lazysizes library automatically writes out the sizes
attribute when lazy loading, and is discussing how to automatically sizes
natively for lazy loading pictures.
sizes can be larger than viewport
Quick instructions on sizes
. Suppose there is an effect on your website so that when you click on the image, the image will "magnify". It might expand to fill the entire viewport, or it might zoom in more so you can see more details. In the past, we might have had to click to switch src
to switch to higher resolution versions. But now, assuming that a higher resolution source is already in srcset
, you just need to change sizes
property to a large value, such as 200vw or 300vw, the browser should automatically download the ultra-high resolution source for you. Scott Jehl has an article about this technology. (Article link should be inserted here, the original text is missing)
(The content of the rest is too long, and it is recommended to process it in segments or selectively translate it as needed)
The above is the detailed content of HTML Responsive Images Guide. For more information, please follow other related articles on the PHP Chinese website!

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

Article discusses CSS Flexbox, a layout method for efficient alignment and distribution of space in responsive designs. It explains Flexbox usage, compares it with CSS Grid, and details browser support.

The article discusses techniques for creating responsive websites using CSS, including viewport meta tags, flexible grids, fluid media, media queries, and relative units. It also covers using CSS Grid and Flexbox together and recommends CSS framework

The article discusses the CSS box-sizing property, which controls how element dimensions are calculated. It explains values like content-box, border-box, and padding-box, and their impact on layout design and form alignment.

Article discusses creating animations using CSS, key properties, and combining with JavaScript. Main issue is browser compatibility.

Article discusses using CSS for 3D transformations, key properties, browser compatibility, and performance considerations for web projects.(Character count: 159)

The article discusses using CSS gradients (linear, radial, repeating) to enhance website visuals, adding depth, focus, and modern aesthetics.

Article discusses pseudo-elements in CSS, their use in enhancing HTML styling, and differences from pseudo-classes. Provides practical examples.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
