Picture tag behave like a div

Viewed 289

I need help to understand one thing: a picture tag behaves like a container for an img tag if its parent has 'display: flex'. If I add width:50% to img, it doesn't make img 50% of div but make img 50% of picture. If I add width:50% to picture and width: 100% to img it works as I need. But why do I need to add style to the picture to make img 50% of div? I thought that picture is just an invisible wrap to keep sources. But it behaves like a div. Why?

<div style="display: flex;">
    <picture style="width: 50%">
        <source srcset="img/cmn/logo.webp" type="image/webp">
        <img src="image.png" alt="img" style="width: 100%;">
    </picture>
</div>
2 Answers

When using a <picture> element, it effectively takes over as the principal element of its content, the content becomes dependencies of the picture element. So how this works is expected.

You now work with the picture element and not with the individual image element(s) inside of it. This means you have to scale the picture element and not anything inside of it.

That said, it's common practice in responsive web design to always have img elements fill the full width of their parent container (width: 100%;), for responsiveness to become easier to handle and more predictable.

Authoritative information: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture

From the specification

The picture element is a container which provides multiple sources to its contained img element

So yes, it behaves like a div for the image and in your case the picture is the flex item (not the image)

Related