Auto-width image with `srcset` attribute - html

Say I have the following image:
<img src="//picsum.photos/100" srcset="//picsum.photos/100 100w">
It appears that the sizes attribute I have not included defaults to 100vw, hence the small image is upscaled to the width of the viewport.
What do I do if I don't want this behavior, but instead want the image to default to its intrinsic size?
I would expect that this image would default to 100px in width on a normal display, and 50px on a 2x (retina) display.
If I specify my own sizes attribute of 100px, this doesn't solve the problem of displaying it at 50px when on a retina display.
The reason I need this behavior is because in my system users are allowed to upload images of any size and place them on a page, and I am generating an srcset with multiple steps up to the max size of their image, and I need a way for the image to display at the correct width given the size of the image and the pixel density of the user's screen.
Can this behavior for auto-width images be achieved using srcset?
In my research I've found this article which addresses the issue directly. The author recommends adding the width attribute with the maximum size of the image to revert what the sizes attribute does to the image's intrinsic size. However, he does not address how to make this work with differing pixel densities.

Unfortunately it seems there isn't a way to have an image with srcset default to its natural size, taking DPR into account. The sizes attribute, which defaults to 100vw if not set on an image with srcset, redefines the image's intrinsic width, and there doesn't seem to be a way to reset it without providing an explicit width yourself.
In my specific situation I discovered that we were already storing the user's DPR in a cookie, so server-side I've started setting the width attribute on images to the max width of the image divided by the user's DPR. This prevents the image from being displayed larger than the original size, and ensures that the image is sized appropriately for devices with high pixel densities.
Of course, you'll probably want to combine this with max-width: 100%; in your CSS to prevent the image from displaying larger than its container.
Example solution:
<!-- Width generated server-side for standard displays: -->
<img src="//picsum.photos/100" srcset="//picsum.photos/100 100w" width=100>
<!-- Width generated server-side for displays with a DPR of 2: -->
<img src="//picsum.photos/100" srcset="//picsum.photos/100 100w" width=50>

Related

How does the browser determine which srcset image to load when no sizes attribute is present?

I have an image that gets displayed in various sizes on my website:
The website is responsive and the apparent image size is often the size of the browser, with some exceptions when the browser is very wide. So, the image's width can vary between 200 and over 1000 pixels.
We want the image to be displayed in native resolution on high-resolution devices (Retina).
So, our image is present in three resolutions, let's call them i1.png, i2.png and i3.png.
What I would like to do is just this:
<img src="i1.png" srcset="i1.png 420w, i2.png 840w, i3.png 1260w" />
In my opinion, the browser should have enough information to figure out which image it needs.
On a standard-resolution device (no retina screen), it just takes the width of the <img /> element and then loads the image that has a width higher or equal to the width of the element. E.g. if the image element is 600px wide, then it will load i2.png.
On a retina device, it would just multiply the width of the <img /> element with the device-pixel ratio. E.g. on a "2x" device, it would load i3.png for a 600px image, because 2 x 600 = 1200, so it would need the image with a width of 1260px.
It seems the browser indeed does something like that, but in some cases it would load the 840px image even though the 420px image would be enough.
What factors does the browser use to determine the size of the image to load?
Is it using CSS rules to determine the image's apparent width?
Or does it ignore CSS and just look at width and height attributes on the <img />, if present?
What if some parts of CSS are not yet loaded?
Crucial point: I do not want to use the sizes attribute, because I would need media queries for all possible combinations of device-pixel ratios and browser window widths. This should not be necessary, because as I said, the browser should have enough information.
I checked the Mozilla Docs about the topic, but they say that if sizes is omitted, then we need to use 2x descriptors (instead of 420w descriptors) in the srcset attribute. This is useless for my scenario: the goal is to have the browser find out which image to load, not just based on device-pixel ratio, but also based on responsiveness.
Seems that the browser does not respect any CSS to decide which image to load. After all, it is not clear which CSS files have already been loaded when the image starts loading.
Instead, it treats each image as if it was stretched to the full page width. If the screen is non-retina and 600px wide, it would load the next-higher image size (840px in the above example), regardless of the actual size that the image would occupy on the screen.
For retina screens, it would just multiply the required image width by the device-pixel ratio.

Responsive full-width images and srcset

I have a site where I want some full-width images (they'll be cropped vertically, for a parallax look). I want to I've read a bunch of articles on srcset and sizes and tried a few things, but I can't figure out (a) whether I need to use "sizes" at all, and (b) especially without sizes, how the browser will choose which image to load.
For concreteness, here's an image spec:
<img src="/images/full/2c8n.jpg" srcset="
/images/320/2c8n.jpg 320w,
/images/640/2c8n.jpg 640w,
/images/1024/2c8n.jpg 1024w,
/images/full/2c8n.jpg">
This is in a full-width container div so the image should go edge to edge.
I'd like it to load the smallest one on mobile and the largest one (the /images/full one) on big desktops, but that doesn't seem to be happening. I've seen that it's possible to use x style as well, but I'm not sure how I'd choose which image to use with each scale factor, if that's even the right way to do it. Any idea what I'm doing wrong and what's the proper way to do this?
The documentation is pretty unclear about the sizes attribute. What I've been able to determine is that it only affects what size to render the image, and NOT image selection. So, sizes="(max-width: 500px) 50vw, 100vw" tells the browser:
if the viewport is up to 500px wide, render the image at 50% of the viewport (50vw)
if the viewport is 501px or larger, render the image at 100% of the viewport (100vw)
For the srcset attribute, the browser takes a look at your list of images, guesses at what size the slot is it should fill and then chooses the next size up. So, edge to edge as per your requirement, this is how it would choose which file to use:
Viewport width up to 319px -> /images/320/2c8n.jpg
VW 320px to 639px -> /images/640/2c8n.jpg
VW 640 to 1023 -> /images/1024/2c8n.jpg
VW 1024 and larger -> /images/full/2c8n.jpg
I've also read, but haven't verified yet, that it uses the first image it finds that fits the requirements between the src and srcset tags. The order of the attributes may make a difference. Again, read but not verified.

w and px of the srcset attribute in html

In the srcset attribute of img element in html, we can specify either the width or the pixel density of each source. We use w to specify width and x to specify pixel density. I have some questions about w and x.
Does 500w mean that the width of the image is 500 pixels? If so, why is it w and not px, as used when in the size attribute?
Does 1x means a pixel density of 72pixels/inch
Why does an image have pixel density? I thought pixel density means the number of pixels within a physical length/space. For example, the number of pixels per inch. But a digital image doesn't occupy a physical length/space, it only occupies a number of pixels. So what does the pixel density of a digital image mean?...This is my guess, please tell me if I'm right: An image only occupies a number of pixels, but it could have been intended for a physical length. For example, an image of a button of 144 pixels width was intended to occupy a physical space of 1 inch. Therefore, it was intended for a device of 2x. We tell the browser this by specifying 2x in the srcset attribute. To sum up, the pixel density means the pixel density of the system the image is intended for.
#1. The 'w' value that appears to the right of each file listed in the srcset attribute of the <img> tag is known as the "w descriptor." The value of each 'w' descriptor is the intrinsic width, in pixels, of the file the 'w' descriptor is associated with. "Intrinsic width" means the native width of the image when it is was originally created or the last time its width changed. You can view a file's intrinsic width in Photoshop or the Windows 10 Photo Viewer (click the three-dot menu "..." and select File Info). "px" is not used to describe intrinsic width because it is used to describe various other types of image widths. The 'w' descriptor describes a specific type of image width that is measured in pixels - intrinsic width - and is used only with the srcset attribute of the <img> tag.
#2. "1x" does NOT mean a pixel density of 72 pixels per inch. That's because pixel density is NOT device resolution. Pixel density is the ratio of browser image width in pixels (known as "CSS pixels") to the native pixel width of the device's display screen. Pixel density has nothing to do with device resolution.
#3. An image does NOT have pixel density. It has only two types of width measurements - both in pixels. One width measure is the width the browser is displaying the image at. The other width measure is the intrinsic width of the image (see #1). For example, suppose I have an image whose intrinsic width is 800px wide. Also suppose that the browser is displaying the image at 650px wide. These two measures are not related in any way (this is NOT pixel density!) - they're just two different ways an image can be viewed which results in two different width measurements.
I've answered your questions directly, without any other context or explanation, and I'm certain that you are scratching your head saying, "That didn't help!" That's the exact same reaction I had when I first started to educate myself about how inline images (images that are specified with the <img> tag in HTML) are selected and displayed by browsers. I suggest you read this post to begin to gain a thorough understanding about how inline images are specified in HTML markup and how browsers select the appropriate image from the srcset attribute of the <img> tag. You can expect several weeks of study before this topic comes into sharp focus. And when you've finished mastering inline images, background images are waiting for you to master with a completely different set of rules. :>)

Can the CSS background-image property be used to resize the background image?

I would like to find out how to present a banner or logo on a responsive design but I can't find a question that is not flagged as bad or likely to be closed. I've tried numerous ways of phrasing the question and none of them are liked. So, I have no idea how to even present this question or even where to begin to look for the answer or how to ask the question. PLEASE, PLEASE give me an idea of how to word this so someone will see my question. I've tried web searches but nothing addresses the issue and I cannot even figure out how to work it.
In case someone sees this, what I am doing is taking a site that was not responsive and had a banner that was 1100 px wide by 110px in height. The trend seems to be to move away from such banners and use logos that are square or round instead or to use text for branding. If I just reduced the size of the banner to 500px wide then the height would proportionally decrease to only 40 or 50px if a percent value was used. That clearly won't look good on a small screen.
Also, if I reduced the image to a more square dimension the image isn't actually resizing by percent values when the CSS background-image style is used instead of an img tag surrounded by div tags. I haven't found a way to control alignment and size using percent values on the background-image property of a container. I could tell my client that we shouldn't use a wide banner in a responsive design but I don't know if that means I am missing an option.
A different image seems to be required on smaller displays using media queries. Can alignment and resizing as percent values be used with the background image CSS style or should different images be served using the img tag?
Lastly, on a high pixel density display tablet or even smartphone serve a large image due to the number of pixels wide being greater than 900px or 1000px? With high-density displays, it seems that even a smartphone could have a width greater than 1000px but that may not look right.
this will size it:
.img-class {
background-image: url('path/myImage.png');
background-size: 200px 200px;
}
first value is width, second value is height, you can also use %, or to scale the whole thing use a single value like for example: background-size: 80%;
A different image seems to be required on smaller displays using media
queries. Can alignment and resizing as percent values be used with the
background image CSS style or should different images be served using
the img tag?
Yes as long as you scale it down and not up, or it blurs out.
Lastly, on a high pixel density display tablet or even smartphone
serve a large image due to the number of pixels wide being greater
than 900px or 1000px? With high-density displays, it seems that even a
smartphone could have a width greater than 1000px but that may not
look right.
Just be sure your images are 'retina ready' and that's all, meaning if you want to place on your website a 200x200 px image, create it 400x400 px instead, then using css you force it to always be 200x200, so it will read a 400x400 and resize it to 200x200 making it not blurred on mobile.
Side note: If you have graphic images and not photographs, i recommend you using svg (vector images) now supported on all browsers, that are scalable so retina ready by default let's say, and way smaller in size.

Is it still relevant to specify width and heigth attribute on images in HTML?

I found a similar question here, with the answer: "you should always define the width and height in the image tag." But it is from 2009.
In the meantime, many things has changed on frontend. We are all doing responsive page design now, for many devices and sizes simultaneously (mobile, tablet, desktop...).
So, I wonder is it still necessary to specify the width and height attributes, and for what reason (for responsive, page speed, SEO...)?
An img element has width and height attributes, but they're not required under any DOCTYPE.
Width and height attributes were only 'required' or relevant to reserve the space on the page and prevent the page moving around as it loads - which is important. This can be achieved using CSS instead providing the CSS loads quickly enough - it is likely to load before the images anyway, so all should be good.
It is also possible (and valid) to specify just one attribute, width or height and the browser will calculate the omitted value in order to maintain the correct aspect ratio.
You can specify percent values in the attributes if required. You don't need to use CSS for this, if that is what you are implying.
Also, it is relevant to add - Under HTML5 the width and height can only take a pixel value, in other words a valid non-negative integer.
Whether you use the width and height attributes can depend on your design. If you have lots of differently sized images, do you want to lump all the dimensions in the CSS or include them with the img?
YES, you want to declare the width and the height of an image in 2016.
To make them retina-ready
If you want your image to be retina-ready, you should define a width and an height lower than the actual pixels. If the image is 800x600 specify <img width="400" height="300" />.
To avoid page jump
Without the width and the height the image does not know how large it is, which causes an unwanted jump in the page as it loads (it reflows). Declaring height and width solves this problem.
Note that:
Images with a defined width and height can still be responsive. Simply add max-width and max-height to your CSS. This will cause the image to scale down (not up) when it does not fit the screen (see this sweet retina-ready, responsive kitten). Defining a min-width and min-height will do the opposite.
Adding a huge amount of compression to your JPG (around 50%) to keep the file size low is recommended when you use a single (relative large) image for all screen sizes.
Well, the basic answer to this question (as with most coding issues) is this: it depends on the situation at hand.
I would say that the “best practice” of always specifying the height and width attributes of images making a significant difference to page rendering speeds hark back to the days when designers laid out their websites using tables and spacer GIFs. We have come a long way since then.
An indication for the future is the introduction of the new picture element being drafted into HTML. The picture element is effectively a wrapper for the existing img element, which allows you to specify several images of different sizes via a source element, and the user-agent itself actually determines which version is used.
<picture>
<source media="(min-width: 64em)" src="high-res.jpg">
<source media="(min-width: 37.5em)" src="med-res.jpg">
<source src="low-res.jpg">
<img src="fallback.jpg" alt="This picture loads on non-supporting browsers.">
<p>Accessible text.</p>
</picture>
As you can see from this example code above (taken from the Intel Developer Zone's article on the HTML5 picture element) there are no height or width attributes on the img element itself.
Here are a selection of resources that will help you to decide the most appropriate method of declaring image sizes:
Responsive Images Community Group
W3C Working Group Note: Use Cases and Requirements for Standardizing Responsive Images
WHATWG HTML Living Standard: The picture element
Good standards are always worth a recommendation. With a little extra code it's quite easy to merge static (px) values of the img tag and generic (em, %) values supplied by CSS. And simpler still, get rid of the img tag altogether and set the picture as background of a div with a unique ID. If you have multiple images, use sprites and assign each picture to its corresponding div. Your mark-up sources would then look something like <div id="image_001"></div> - that's all. Scales all by itself; no need for bloatware like JQuery, etc.
If we're talking 'bout responsive, you may use bootstrap (if not, start doing this).
When working with images, you should add the class img-responsive, this will modify the width of the image if necessary and the height will be auto, so if width decreases, height will decrease too.
You will always have an image that keeps the same % of its container and will never loose the aspect ratio.
There's no relation with SEO and image size declarations.
Page speed will be the same always, so if the image is 800 x 600 px, you'll load the full image, even if you declare it as 60 x 40 px.
You must think that, even using img-responsive, the max width and height of this image will be the real size of the image. So if we have a 800 x 600 px image, it will not enlarge it (because it'll become loosing quality).
So in 2016, it's recommendable to NOT declare height and width of an image. Instead use bootstrap's img-responsive class, other responsive framework class that gets the same result, or hand-made the proper jquery and css to reach the same.
Hope it helps!
Yes, It is still relevant to specify width and height attribute on images in HTML.
Images often take longer to load than the HTML code that makes up the rest of the page. It is, therefore, a good idea to specify the size of
the image so that the browser can render the rest of the text on the
page while leaving the right amount of space for the image that is
still loading.
Hence, specifying width and height attribute on image will improve the webpage performance by protecting from delay in loading.
Yes, it is necessary to add height and width attributes to the img tag along with the src and alt attributes to prevent page-jumping. When our page loads, the specified space will be preserved for the image so that the it can occupy that place peacefully.
But, there is another problem that will arise here Responsiveness.
Once we give height and width attribute to img tag, the image will tend to stay in the same height for all screen-sizes which will make the image to shrink.
To avoid this, we need to add height: auto; to the image in the CSS file.