为什么 max-width 上的媒体查询不起作用?

Why isn't media query on max-width working?

我想使用媒体查询控制徽标的大小。

我的logo原来width210px.

我希望它在屏幕 width 大于 56.865em 时为 166px,在小于此 width 时为相同,即对于移动网站.

我为此编写了以下代码:

@media only screen and (min-width: 56.875em){
  .site-branding img{
    max-width: 166px;
  }
}

@media only screen and (max-width: 56.875em){
  .site-branding img {
    max-width: 166px !important;
  }
}

只有第一个代码块有效。为什么没有第二个工作? (缩小屏幕宽度后,logo的width又变成了210px)。

是否有任何规则不能同时使用 minmax 媒体查询来控制同一元素?

max-width 规则将不起作用,因为它被 min-width 覆盖,因为两者具有相同的值。

一种简单的方法,而不是 2 media queries 只是简单地在一般 CSS 中设置徽标的 width,然后应用媒体查询:

  • 通过使用 max-width

    的非移动方法

  • 通过使用 min-width

  • 的移动优先方法

带有 max-width

的选项

.logo img {
  width: 210px
}
@media (max-width: 56.865em) {
  .logo img {
    width: 166px
  }
}
<div class="logo">
  <img src="//lorempixel.com/300/300">
</div>

选项 min-width

.logo img {
  width: 166px
}
@media (min-width: 56.865em) {
  .logo img {
    width: 210px
  }
}
<div class="logo">
  <img src="//lorempixel.com/300/300">
</div>


更新

First, I want the logo size 166px all the time.

因此,如果您想要始终让徽标的 width 始终处于 166px,这意味着您希望将当前的 210px 更改为 166px

那么你不需要媒体查询。假设您正在更改自定义 CSS 文件并且您可以't/want 更改基本 CSS 文件(其中包含 width:210px),您只需要更具体一些。

MDN and in W3C Specs

中查看有关 CSS 特异性的更多信息

/* emulating Base CSS */

.logo img {
  width: 210px
}
/*being more specific */
.header .logo img {
  width: 166px
}
<div class="header">
  <div class="logo">
    <img src="//lorempixel.com/300/300">
  </div>
</div>

这让我发疯,但我发现在 @media 之前注释掉文本会阻止该语句。

<!-- DO NOT COMMENT LIKE THIS BEFORE @media -->
/* USE THIS Comment version */

希望对大家有所帮助!