@media queries and image swapping [closed]

℡╲_俬逩灬. 提交于 2019-12-17 10:42:32

问题


I want the image in my site to completely change when the browser is resized.

I've been using media-queries, but I can't seem to get it right. Any thoughts/tips?


回答1:


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




回答2:


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>



回答3:


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>


来源:https://stackoverflow.com/questions/27853884/media-queries-and-image-swapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!