【问题标题】:Media query not working with background images [duplicate]媒体查询不适用于背景图像[重复]
【发布时间】:2020-10-11 18:35:56
【问题描述】:

我的网站上有一个具有以下样式的 div:

#image {
    background-image: url(../Images/logo.png);
    border-right: 1px solid black;
    height: 80px;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
    width: 200px;
}

这实际上是公司的标志。我想将此徽标更改为较小的屏幕尺寸,因此我进行了以下媒体查询:

@media only screen and (max-width: 930px){
    #image {
        background-image: url(../Images/logoImage%20copy.jpg); 
        width: 88px; 
    }
}

但是图像仍然没有改变。然后我添加了!重要:

@media only screen and (max-width: 930px){
    #image {
        background-image: url(../Images/logoImage%20copy.jpg); !important
        width: 88px; !important
    }
}

但它仍然没有改变背景图像。

除此之外媒体查询工作正常(因为其他属性工作正常)

我还包括html代码:

@media only screen and (max-width: 930px){
    #image {
        background-image: url(http://placehold.it/80x88); !important
        width: 88px; !important
    }
}

#image {
    background-image: url(http://placehold.it/200x80);
    border-right: 1px solid black;
    height: 80px;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
    width: 200px;
}
<div id="image"></div>
    <!--Some Code-->

【问题讨论】:

  • 能否包含您的 HTML 代码,以便我尝试重现您的问题?
  • @itsanenewabstract 我添加了示例 html 代码

标签: html css media-queries background-image


【解决方案1】:

像这样试试。媒体查询应低于默认规则,以便正确覆盖它。

另一方面,!important; 之前而不是在之后,但不是必需的,至少对于这个 sn-p。

最后,代码 sn-p 在 930px 作为媒体查询断点的 sn-p 预览中将无法正常工作,因为 sn-p 显示在 iframe 中并且其视口小于 930px,因此默认规则将始终为被 sn-p 预览中的媒体查询覆盖。要避免这种情况,请单击展开 sn-p,在空白页中查看 sn-p。

#image {
    background-image: url(http://placehold.it/200x80);
    border-right: 1px solid black;
    height: 80px;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
    width: 200px;
}

@media only screen and (max-width: 930px){
    #image {
        background-image: url(http://placehold.it/80x88);
        width: 88px;
    }
}
<div id="image"></div>
    <!--Some Code-->

【讨论】:

    猜你喜欢
    • 2012-12-17
    • 2014-08-14
    • 2016-11-30
    • 1970-01-01
    • 2015-06-08
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    相关资源
    最近更新 更多