skip to Main Content

Hello is this correct to show srcset in img tag?

<img src="png-shat-should-be-showed-when-under-400px.png" alt="image" srcset="png-shat-should-be-showed-when-under-400px 400w, png-shat-should-be-showed-when-over-400px.png 400w" sizes="(max-width: 400px) 400px, 50vw">

I want to one img when under 400px viewport, and second port when viewport is over 400px.
lets say i have 2 image

adding dimensions in tag

1. png-shat-should-be-showed-when-under-400px.png
2. png-shat-should-be-showed-when-over-400px.png

2

Answers


  1. Your tag should look like this:

    <img
    src="under-400px.png"
    alt="image"
    srcset="under-400px.png 400w, over-400px.png 800w"
    sizes="(max-width: 600px) 400px, 800px" />
    

    In the srcset attribute you would use the intrinsic size of the image. That means the actual true and correct width of the image. The srcset will not resize your image for you. Remember that in the srcset you will use w and not px.

    You need to understand media queries to understand the sizes attribute. The max-width shown in the media query defines the breakpoint where the browser will alternate the images. If your viewport width is smaller than this breakpoint it will show the image that is smaller and if your viewport width is larger than this breakpoint it will show the larger image.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search