skip to Main Content

Is there a way to use media query on html? I need to put a image like a banner centralized on my page, when the screen it’s less than 768px it’s shows a smaller image but when the screen grows to more than 768px it should replace the smaller image to another image that I have that is bigger. Is there a way to make this only on html and inline css? I should’nt use an external file.

4

Answers


  1. You can use a div which has a background-image instead of the img element. Then you can add a media query in CSS where you define a smaller size and a different background-image for the mobile version.

    Login or Signup to reply.
  2. You can achieve this using inline CSS:

    <div style="text-align: center;">
      <img src="small-banner.jpg" alt="Small Banner" style="max-width: 100%;">
    
      <style>
        @media (min-width: 768px) {
          img {
            content: url(large-banner.jpg);
          }
        }
      </style>
    </div>
    
    Login or Signup to reply.
  3. If you have to do in one file, in html, it is not possible to do in img tag. But you can do something like this, using embedded style element. For example:

    <html>
       ...
       <style>
          .large-img {
            display: none;
          }
          .small-img {
            display: block;
          }
          @media(min-width: 768px) {
            .large-img {
              display: block;
            }
            .small-img {
              display: none;
            }
          }
       </style>
       <body>
          ...
          <img class="large-img" src="largeImage.png">
          <img class="small-img" src="smallImage.png">
          ...
       </body>
    </html>
    
    Login or Signup to reply.
  4. You don’t even have to use CSS for this. Use the <picture> element; it is widely supported by modern browsers:

    <picture>
      <source
        srcset="path/to/bigger/picture"
        media="(min-width: 768px)"
      >
      <img src="path/to/smaller/picture">
    </picture>
    

    Try it:

    <picture>
      <source
        srcset="https://picsum.photos/700"
        media="(min-width: 768px)"
      >
      <img src="https://picsum.photos/400">
    </picture>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search