Acccording to MDN the <picture>
element simply takes the content of the <source>
and puts it inside the space defined by the <img>
tag:
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.
(My emphesis)
Therefore, I would expect that the classes on the <img>
tag would still appear to the end user, regardless of which (or any) <source>
material is used.
My Testing:
But I had not checked this. So I decided to run a few tests with image types (PNG / JPG / Webp) and <picture>
elements:
.one {
border: 3px solid #f00;
}
.two {
border: 3px solid #0f0;
}
.thr {
border: 3px solid #00f;
}
.fou {
/* Picture Element */
border: 3px solid #333;
display: inline-block;
}
<picture class='fou'>
<source srcset="https://www.gstatic.com/webp/gallery/3.webp" type="image/webp" class='thr'>
<source srcset="https://developers.google.com/web/fundamentals/design-and-ux/responsive/img/art-direction.png" type="image/png" class='two'>
<img src="https://images.pexels.com/photos/163016/crash-test-collision-60-km-h-distraction-163016.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="" title="" class='one'>
</picture>
From the above example, and from editing it and playing with it by
- Rearranging the
<source>
materials.
It can be easily found that:
The <source>
elements are NOT hidden on the page,but do not contain the graphical content.
Regardless of the <source>
used, the <img>
element is always the element that contains the picture graphic (sometimes called an image (WTF?) ) .
The <picture>
container object always exists but is a container such as <figure>
in HTML5. It should not be given CSS styling intended for contents such as <img>
.
Conclusion:
The code above (and its fiddles and edits) shows that all elements are present in the HTML, but the only one that is the image is the <img>
element.
Therefore, you should not be applying any styling or CSS whatsoever to <source>
elements and only container stylings should be applied to <picture>
elements.
You Asked:
Do I need to repeat the class attribute for each source inside a picture element?
The Answer:
The answer is NO. You should style the <img>
element ONLY.
Example:
<picture>
<source srcset="/images/example.webp" type="image/webp">
<source srcset="/images/example.png" type="image/png">
<img class="usp-pics pic1" src="/images/example.png" alt="something" title="">
</picture>