用媒体查询替换图像不起作用

Replace image with media query not working

我正在使用 HTML 模板,我正在尝试使用媒体查询根据浏览器大小替换站点的徽标。

我正在尝试我在这里找到的技术:@media queries and image swapping

我的 custom.css 文件有这个代码:

.test-mobile-logo{
   display: none;
}

@media only screen and (max-width: 500px){           
    .test-main-logo{
     display: none;
   }

   .test-mobile-logo{
     display: block;
   }
}

我的 html 文件具有此徽标代码:

<div class="logo"> 
                <a href="index.html" >
                    <img src="images/logo-dark.png" alt="" class="test-main-logo">
                    <img src="images/logo-main.png" alt="" class="test-mobile-logo">
                </a> 
            </div>

该页面同时显示了两张图片。但是当我删除我的 style.css 文件时,图像终于一次显示一个并正确替换。

style.css 文件:http://demos.webicode.com/html/lucian/html/css/style.css

我不确定冲突是什么,我对 CSS 还是个新手。有人有什么想法吗?

您 css 中的这种样式覆盖了您的显示样式。

img {
  display: inline-block !important;
}

删除 !important 以使您的媒体查询正常工作。

如@VincentOrback 所述,只需从 img 选择器

中删除 !important

Better technique: use background-image instead and just change the url, or (even better) use CSS Sprites

我同意@HenrikhKantuni 使用背景图片并在 css 媒体查询中更改背景图片。

否则用户将始终下载 2 张图像,这是一个不必要的 http 请求和用户请求的千字节数,尤其是在移动网络上,您希望尽可能减少此数量。