0

If we want to use different pictures of different sizes according to a screen break. What would be the best way to approach this?

For instance

<picture class="image-wrapper">
    <source srcset="images/image-product-desktop.jpg" media="(min-width: 800px)"/>
    <img class="image" src="images/image-product-mobile.jpg" alt="chanel perfume bottle lying down with leaves draped around">
</picture>

The issue above is that I can provide height and width for the mobile image, but if the user loads on the desktop, I don't understand yet, how to provide fixed width for that. I should add that the two images will have a different art direction. They will not have the same intrinsic width or height.

I found an excellent SO post below which is relevant, but hasn't responded to this precise situation. Here it is for reference.

Image elements do not have explicit width and height

Lauro235
  • 121
  • 1
  • 8

1 Answers1

0

Okay so in my solution, I moved away from srcsets and used a div with a background image. The image displayed is decided by CSS.

To handle the jank... I started by finding the dimensions of my picture eg.

Mobile image Height = 240, Width = 343

Desktop Image Height = 450, Width = 300

I then added this to the root as a var with calc()

:root {
/* height / width * 100% (not width / height) */
  --mobile-aspect: calc(240 / 343 * 100%); 
  --desktop-aspect: calc(450 / 300 * 100%)
}

After adding padding-top to the future-images parent divs I added a media query

.image-wrapper {
  padding-top: var(--mobile-aspect);
  position: relative;
  background-image: url("../images/image-product-mobile.jpg");
  background-repeat: no-repeat;
  background-size: contain;
}

@media screen and (min-width: 800px) {
  .image-wrapper {
    padding-top: var(--desktop-aspect);
    background-image: url("../images/image-product-desktop.jpg");
  }
}

At this point. No complaints from Light house and no jankiness! Hope this helps.

Great resources
Clear Video description
In Depth CSS Tricks Article

Lauro235
  • 121
  • 1
  • 8