Home > database >  how to use html picture element?
how to use html picture element?

Time:10-15

So I'm trying to display multiple images using the picture tag and whatever I do, the pictures I'm trying to display doesn't seem to appear at all, I don't know what's the problem so I don't know how to fix it.

<div >
            <div >
                <picture>
                    <source media="(min-width: 600px)" srcset="images/gallery-01.png">
                    <source media="(min-width: 900px)" srcset="images/gallery-02.png">
                    <source media="(min-width: 1100px)" srcset="images/gallery-03.jpg">
                </picture>
            </div>
        </div>

CodePudding user response:

Are you 0 sure that your srcset= "images/gallery-01.png" leads to the correct image? If that's not the problem then I would recommend trying <img src="images/gallery-01.png">. Here's the full code,

<div >
            <div >
                <picture>
                    <img alt="Image1" src="images/gallery-01.png">
                    <img alt="Image2" src="images/gallery-02.png">
                    <img alt="Image3" src="images/gallery-03.jpg">
                </picture>
            </div>
        </div>

CodePudding user response:

<img> element is required, <source> is optional

Your snippet doesn't have any <img> tag, which is required. <source> elements are optional, which might occupy the space presented in <img>

Accodring to MDN page:

The <picture> HTML element contains zero or more <source> elements and one <img> element to offer alternative versions of an image for different display/device scenarios.

The browser will consider each child <source> element and choose the best match among them. If no matches are found—or the browser doesn't support the <picture> element—the URL of the <img> element's src attribute is selected. The selected image is then presented in the space occupied by the <img> element.

See the updated snippet below. The only change here (except the picsum.photos placeholder images) is the addition of <img> tage. In this example, the /300 image will be shown by default, but if/when the browser supports the <picture> element and certain media query matches a particular <source> image will replace the default image.

<div >
  <div >
    <picture>
      <source media="(min-width: 600px)" srcset="https://picsum.photos/200">
      <source media="(min-width: 900px)" srcset="https://picsum.photos/400">
      <source media="(min-width: 1100px)" srcset="https://picsum.photos/600">
      <img src="https://picsum.photos/300" alt="" />
    </picture>
  </div>
</div>

  •  Tags:  
  • html
  • Related