HTML picture Element
HTML <picture> element allow developer to define multiple sources for a image enabling responsive image loading. This is particularly useful for optimizing performance on different devices and screen sizes. The <picture> element contains one or more <source> elements and an <img> element as the fallback.
2024-08-21 14:15:10 - Sakala Code
HTML picture Element Syntax
<picture> <source srcset="image-small.jpg" media="(max-width: 600px)"> <source srcset="image-large.jpg" media="(min-width: 601px)"> <img src="default-image.jpg" alt="Description of the image"> </picture>
Responsive Images with <picture> tag
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Picture Element with Example</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
}
img {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<h1>SakalaCode Responsive Image with the <picture> Element</h1>
<picture>
<!-- Image for small screens (max-width: 600px) -->
<source srcset="small.jpg" media="(max-width: 600px)">
<!-- Image for large screens (min-width: 601px) -->
<source srcset="large.jpg" media="(min-width: 601px)">
<!-- Fallback image for unsupported browsers -->
<img src="default.jpg" alt="Beautiful scenery">
</picture>
</body>
</html>
Using srcset and sizes Attributes:
<picture> <source srcset="image-400.jpg 400w, image-800.jpg 800w" sizes="(max-width: 600px) 100vw, 50vw"> <img src="default.jpg" alt="A default image"> </picture>