0

I want to build a simple image-lightbox where an image is displayed together with its caption. The image and the caption should be displayed in a single column and the image should scale so that it and the caption fit within the viewport of the browser.

I have this working using the <img>-tag (see the current code below), but I can't seem to get it to work with the <picture> element, which I need in order to use multiple image formats.

I don't understand how the <picture> and the <img> element which it contains work together to calculate the final size of the image and I don't understand how I can get the <picture>-element to work in my grid based column layout. Any help here would be greatly appreciated.

The working example:

body {
    padding: 0 0 0 0;
    margin: 0 0 0 0;
}

.lightbox {
    width: 100vw;
    height: 100vh;
}

.lightbox figure {
    display: grid;
    max-height: 100%;
    grid-template-rows: 1fr min-content;
}

.lightbox figure img {
    max-height: 100%;
    max-width: 100%;
    object-fit: cover;
    vertical-align: bottom;
    justify-self: center;
}

.lightbox figure figcaption {
    text-align: center;
}
<div class="lightbox">
  <figure>
      <img src="https://placehold.co/6000x4000" alt="">
      <figcaption>Etiam porta sem malesuada magna mollis euismod. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Curabitur blandit tempus porttitor. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.</figcaption>
    </figure>
</div>

The change I'd like to make to the markup while retaining the layout:

<div class="lightbox">
  <figure>
    <picture>
      <source srcset="...">
      <source srcset="...">
      <img src="https://placehold.co/6000x4000" alt="">
    </picture>

      <figcaption>Etiam porta sem malesuada magna mollis euismod. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Curabitur blandit tempus porttitor. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.</figcaption>
    </figure>
</div>
Skye Ewers
  • 358
  • 1
  • 4
  • 16
  • The markup seems ok. Did you include the `media` attribute in the `` tag? Example: `` Taken from MDN: "The `media` attribute specifies a media condition (similar to a media query) that the user agent will evaluate for each `` element." https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture – Ferris May 09 '23 at 16:11
  • @Ferris tested that and it didn’t end up changing anything. The picture tag around the image somehow seems to influence the images ability to scale its height and I have no clue why. – Skye Ewers May 09 '23 at 20:09

0 Answers0