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

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

html - Changing image src depending on screen size

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

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

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...