html - 根据屏幕大小更改图像 src

标签 html css twitter-bootstrap

我正在尝试使用媒体查询根据屏幕大小更改图像 src。我试过 background:url(x);但它没有用。我在某处读到我应该改用 content:url(x) ,但是当我这样做时,我得到一个空白页。谁能告诉我我的代码有什么问题?

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");   
     } 
}

最佳答案

这个对我有用。我不知道你是否熟悉这个标签,但它甚至不需要 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>

在这种情况下,“BigImage”将在设备宽度超过 900 像素时显示。大于 480 像素时为“MediumImage”,小于 480 像素时为“OtherImage”。如果您使用“max-width: 900px”而不是 min-width,当宽度超过 900px 时它也会显示。

希望对您有所帮助!

关于html - 根据屏幕大小更改图像 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30460681/

相关文章:

jquery - anchor /按钮在 chrome 上消失,直到使用 Bootstrap 鼠标悬停后才会重新出现?

html - 带有图像的 Flexbox 网格 - 保持纵横比/比例

javascript - 如何使用 HTML/javascript 以预定义的顺序加载图像?

jquery - 无法导航到子菜单,菜单和子菜单之间有空格

打开控制台后 CSS 在 Chrome 中停止工作

twitter-bootstrap - 调整高度以匹配内容的 DIV

javascript - 按下 'enter' 键时删除输入框中的文本

php - 单击链接时 Codeigniter 不显示样式表

html - 具有相同高度的 Flexbox 居中元素

twitter-bootstrap - Google Charts 和 Twitter Bootstrap 选项卡