@media queries and image swapping

喜你入骨 提交于 2019-11-27 12:28:47

In the future please add code you've tried.

if it's an image tag you can use a class. Hide the second image on page load and show + hide image 1 at a certain screen size like so:

HTML

<img src="image.jpg" class="image1"/>
<img src="image.jpg" class="image2"/>

CSS

.image2{
   display: none;
}

@media only screen and (max-width: 500px){ //some value
   .image1{
     display: none;
   }

   .image2{
     display: block;
   }
}

EXAMPLE 1 - SHRINK BROWSER

OR

If it's a background-image you can simply swap the image:

HTML

<div class="example"></div>

CSS

.example{
   background-image: url("example.jpg");
}

@media only screen and (max-width: 500px){ //some value

   .example{
      background-image: url("example2.jpg");
   }
}

EXAMPLE 2 - SHRINK BROWSER

This can be done using the HTML5 picture element which doesn't require CSS for changing img elements on specified media queries. If you're intrested in this approach, do be aware of its browser support which does NOT include IE, though there is a polyfill for older browsers.

<h1>Resize Window</h1>
<picture>
  <source srcset="https://placehold.it/1400x1400" media="(min-width: 1400px)"/>
  <source srcset="https://placehold.it/1200x1200" media="(min-width: 1200px)"/>
  <source srcset="https://placehold.it/800x800" media="(min-width: 800px)"/>
  <source srcset="https://placehold.it/600x600" media="(min-width: 600px)"/>
  <img src="https://placehold.it/400x400" alt="example"/>
</picture>

You can use the content property to insert your image. However, images included like this could be difficult to style. (Run code snippet in full screen before resizing browser)

@media screen and (max-width: 479px) {
    div img {
        display:none;
    }
    div::before {
        content: url("https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg?v=6e4af45f4d66");
    }
}
<p>Resize this window to see image change</p>
<div>
    <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg?v=2bb144720a66" width="200px" />
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!