Table of Contents
HTML Responsive Image Guide: Quick View of Code Snippets
Using srcset/w sizes
Create accurate sizes attributes
More relaxed in sizes
Abstract sizes
"Browser Selection"
This is very strange. Don't the browser already know these things?
sizes can be larger than viewport
Home Web Front-end CSS Tutorial HTML Responsive Images Guide

HTML Responsive Images Guide

Apr 05, 2025 am 09:54 AM

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/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174381805452081.jpg" class="lazy" alt="HTML Responsive Images Guide">
Copy after login

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/imghw/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
  ">
Copy after login

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;
  }
}
Copy after login

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)
  ">
Copy after login

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)
  ">
Copy after login

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="">
Copy after login

"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">
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

How to Use CSS Grid for Sticky Headers and Footers How to Use CSS Grid for Sticky Headers and Footers Apr 02, 2025 pm 06:29 PM

CSS Grid is a collection of properties designed to make layout easier than it’s ever been. Like anything, there&#039;s a bit of a learning curve, but Grid is

Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

See all articles