The power of the HTML image tag and the versatility of the srcset

I am feeling a bit puzzled about how to properly use the srcset attribute within the HTML img tag. Despite reading multiple tutorials online, it seems that things are not functioning as described in those resources. Let's begin with a simple example:

<img src="assets/img/software-developer.jpeg" alt="Some Stuff" srcset="assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w">

In this case, I have two images:

  • assets/img/software-developer.jpeg
    with dimensions of 450x450 pixels
  • assets/img/software-developer-300.jpeg
    with dimensions of 300x300 pixels

Despite my attempts using Chrome Developer Tools for testing, I observe that regardless of the screen size I select, the image being downloaded is always

assets/img/software-developer.jpeg
. This is evident when looking at the currentSrc property under the Properties tab in Developer Tools.

Can someone shed some light on why this is happening? Ideally, I would like:

  • for screens with a width >= 450px, download
    assets/img/software-developer.jpeg
  • for screens with a width < 450px, download
    assets/img/software-developer-300.jpeg

Additionally, I am unsure about what occurs when the screen size is less than 300px:

If the smallest image available is

assets/img/software-developer-300.jpeg
with dimensions of 300x300 pixels, how can I adjust the code to allow it to resize and fit the viewport in such scenarios?

For instance, when using the Galaxy Fold device in Developer Tools with a width of 280 pixels, neither of the images fits the screen size: how should I update my srcset to enable resizing in this instance?

The internet contains abundant information relating to this topic, yet upon initial exploration, things appear somewhat perplexing. As a first step, I decided to conduct small tests focusing on srcset to verify if the expected image is being downloaded. Unfortunately, it appears that the tag is not performing as anticipated. It is clear that I am overlooking something crucial, and I am hopeful that someone here can provide clarification.

Answer №1

It seems like the sizes tag is missing from your code.

sizes is used to define a set of media conditions, such as screen widths, and specify the optimal image size to choose based on those conditions.

To correctly implement this, you should write the code as follows:

<img src="assets/img/software-developer.jpeg" alt="Some Stuff" sizes="(max-width: 449px) 300px, 450px" srcset="assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w">

For more information, you can refer to this link: https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#how_do_you_create_responsive_images

Answer №2

I came to the solution on my own. Initially, using the srcset tag by itself doesn't make much sense; it should always be paired with the sizes attribute.

The srcset informs the browser about the available images, like this:

srcset="assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w"

In simple terms, this attribute tells the browser:

Hey, there are two options for images:

  • assets/img/software-developer-300.jpeg at 300 pixels wide
  • assets/img/software-developer.jpeg at 450 pixels wide

Next, you need to instruct the browser to use the former for screens less than 450px and the latter for screens 450px or wider. This is achieved with the sizes attribute:

srcset="assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w" sizes="(max-width: 449px) 300px,  (min-width: 450px) 450px"

In essence, for screens up to 449px, the 300px image version can be used, while for screens starting from 450px, the 450px version is recommended. However, some phones have screens smaller than 300px (e.g., Galaxy Fold's screen is 280px wide), leading to image cropping. To prevent this, it's necessary to inform the browser that if the screen size is under 299px, resize the image to 100vw. In my particular case, I found that using 75vw instead of 100vw worked better.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Step by step guide on inserting View and Delete buttons in an HTML table populated by JSON data

I've successfully loaded data from a JavaScript file in JSON format into a plain HTML table using JavaScript. Everything is working well so far. I now want to enhance the table by adding two buttons, View and Delete, that when clicked will redirect to ...

How can the data from a factory be utilized within the same controller but in a separate file in an AngularJS application?

When trying to route from home.html to profile.html, there seems to be an issue with the execution of the profile.js script. I have data in script.js that is written in a factory. When the profile button is clicked, the page routes to profile.html, but the ...

Converting HTML code into executable PHP code

I'm having trouble embedding PHP into an HTML file. I modified my .htaccess to recognize HTML files as PHP, but when I attempt to open the .html file in my browser, it gets downloaded instead of being processed and shown. UPDATE: Here is what's ...

having difficulty retrieving the initial selected value of a dropdown using selenium

Situation 1: On the screen, there are two fields named district and territory. Some users have a default value already selected in these fields, with the drop down disabled. Below is the code snippet for reference. <select id="abcd" name="xyz" clas ...

Svelte's feature prevents users from inputting on Mapbox

My goal is to prevent user input when the variable cssDisableUserInput is set to true. Here's what I have within my main tags: <div id=userinput disabled={cssDisableUserInput}> <div id="map"> </div> Within my CSS, I&a ...

Adjust Bootstrap column alignment to left side

Take a look at this full page demo or view it with editor here. The placement of .col-sm-6 .tasks-panel shifts to the right when the previous element .col-sm-6 is not too long, but moves to the left when the previous element is lengthy (try clicking on Ad ...

Editable JSON data within a table using Twitter Bootstrap

How come I am unable to utilize the bootstrap editable table in this manner? <table id="addElements" data-height="299"> <thead> <tr> <th data-field="id" data-align="right">Item ID</th> < ...

The origin of the recipient window does not match the target origin provided when using postMessage on localhost

Currently, I am in the process of developing an application that utilizes single sign-on (SSO) for user authentication. Here is a breakdown of the workflow: Begin by launching the application on localhost:3000 (using a React Single Web Application). A po ...

the overflow issue with Summernote's dropdown menu

I am currently working on a 2 columns layout within 2 divs that have different margins set. In the left column, I have integrated a bootstrap datetimepicker and summernote. While the datetimepicker dialog overflows outside the internal div, I am wondering ...

Tips on inputting pre-made HTML codes into a WordPress post

As of now, I find myself manually inserting the code block below in each of my blog posts: <div class="js-video [vimeo, widescreen]" style="text-align: center;"> </div> I am looking to automate this process by pre-writing the above tags right ...

What benefits does a dynamic website like this offer compared to one that is purely AJAX-based?

There are two main categories of dynamic websites that I define: The first type utilizes languages like PHP to concatenate an HTML page and send it back to clients. On the other hand, the second type uses an HTML template where all interfaces provide JSO ...

How to Fetch Data Using jQuery AJAX in PHP Without Page Refresh

I am trying to prevent the page from refreshing when clicking on a select option, but when I do so, the data does not get updated. Here is the code: echo "<form name='frmtopdevotees' method='post' action='topuser_load.php&apos ...

Utilizing JavaScript to dynamically alter the animation property within CSS

How can I adjust the number of steps in an animation property set within a CSS file? This is the CSS code I am using: #ManSprite{ overflow:hidden; width:200px; height:200px; position:absolute; top:280px; left:140px; background ...

What is the method for showcasing AM and PM in various languages within the input type of time?

I am using the input type="time" like this: <input type="time" id="openTime" name="openTime" value=""> My inquiry is regarding how to localize the display of AM - PM in another language? ...

Automatically adjust the size of a parent div that houses two child divs

@media only screen and (min-width: 900px) { .map_left { display: inline; float:left; width: 100px; height: 100px; border: 3px solid green; } .map_right { display: inline; float:right; width: 100px; height: 100 ...

What could be causing the appearance of a mysterious grey box hovering in the upper left portion of my image and why is the code only adjusting the size of the grey box instead of the entire

I've been working on embedding some JavaScript into my Showit website to create a drag-and-drop feature that displays a collage/mood board effect. Everything is functioning correctly, but I'm running into issues with resizing the images. There&a ...

Switch the text color of the checkbox option

<P><INPUT TYPE="checkbox" NAME="nombre" VALUE="Si"> lorem ipsum <BR></P> I have some code here where I want to change the color of the text lorem ipsum. Currently, I am trying to achieve this by using the following jQuery code: $(" ...

What is the best way to reference the className within nested SCSS when working with Next.js and React.js?

I am working on customizing a navbar that includes a hamburger button. My goal is to change the style, specifically the bar color and the appearance of the hamburger button, upon tapping. I have already attempted using &:active and .activeBar in the SCSS f ...

What is the best way to transform a Bootstrap4 navbar into a mobile-friendly sidebar?

I currently have a Bootstrap 4 navbar (similar to the default navbar that collapses from top to bottom). However, I am looking to convert this navbar into a sidebar for the mobile version. Essentially, I want it to look something like this. <na ...

React JS Bootstrap Dropdown Troubleshooting

I'm facing a challenge in my React.js project while trying to implement a filter. The issue is that the list appears when I click on the button, but it doesn't disappear on the second click or if I click outside the list. Initially, I imported t ...