Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to change the image src depending on the screen size using media queries. I tried background:url(x); but it didn't work. I read somewhere that I should use content:url(x) instead, but when I do so, I get a blank page. Can anyone tell me what's wrong with my code?

HTML:

<div class="container" id="at-header">
  <img class="image" id="logo" src="img/logo_white.png" />
  <img class="image" id="main-img" src="img/desktop_homepage.jpg" />
</div>

CSS:

@media screen and (max-width: 767px){   
    #main-img{      
        content:url("img/mobile_homepage.jpg");
    } 
}

@media screen and (min-width: 768px) {      
    #main-img{      
       content:url("img/tablet_homepage.jpg");
     } 
} 
@media (min-width: 992px){      
      #main-img{        
          content:url("img/desktop_homepage.jpg");  
      } 
}
@media (min-width: 1200px) {    
     #main-img{         
         content:url("img/desktop_homepage.jpg");   
     } 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
446 views
Welcome To Ask or Share your Answers For Others

1 Answer

This one is working for me. I don't know if you're familiar with this tag but it doesn't even need CSS.

<picture>
    <source media="(min-width: 900px)" srcset="BigImage.png">
    <source media="(min-width: 480px)" srcset="MediumImage.png">
    <img src="OtherImage.png" alt="IfItDoesntMatchAnyMedia">
</picture>

In this case "BigImage" Would show when the device width is more than 900px. "MediumImage" when its's more than 480px and "OtherImage" If It's less than 480px. If you had "max-width: 900px" instead of min-width, it would also show when the width is more than 900px.

Hope it helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...