@media queries and image swapping

2019-01-17 12:19发布

问题:

I'm new to CSS and to this forum. But I've been working on a little project where 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>