Using the picture Element for Responsive Images

Here’s a full solution for Using the picture Element for Responsive Images

Step 1: HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Using the &lt;picture&gt; Element for Responsive Images</title>
    <meta name="description" content="Learn how to use the HTML <picture> element to serve responsive images for different screen sizes. Includes example code and explanation.">
    <meta name="keywords" content="HTML5 picture element, responsive images, srcset, media query images, adaptive images">
 
</head>
<body>

<h2>Responsive Image Example</h2>

<p>Resize the browser window to see how the image changes based on screen size.</p>

<picture>
    <!-- Large screens (desktop) -->
    <source srcset="image-large.jpg" media="(min-width: 1024px)">
    
    <!-- Medium screens (tablet) -->
    <source srcset="image-medium.jpg" media="(min-width: 600px)">
    
    <!-- Small screens (mobile) -->
    <source srcset="image-small.jpg" media="(max-width: 599px)">
    
    <!-- Default image (fallback) -->
    <img src="image-default.jpg" alt="A responsive image example">
</picture>

</body>
</html>

Step 2: CSS Code

body {
          font-family: Arial, sans-serif;
          text-align: center;
          margin: 50px;
          background-color: #f8f9fa;
      }
      img {
          max-width: 100%;
          height: auto;
          border-radius: 8px;
          box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
      }

Explanation

  1. HTML <picture> Element

    • The <picture> element allows different images to be served based on screen size.
    • Each <source> has a media attribute that specifies when it should be used.
    • The <img> tag acts as a fallback if no <source> matches.
  2. How It Works

    • If the screen width is 1024px or larger, image-large.jpg is displayed.
    • If the screen width is between 600px and 1023px, image-medium.jpg is displayed.
    • If the screen width is 599px or smaller, image-small.jpg is displayed.
    • If none of the conditions match, image-default.jpg is shown.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top