为什么媒体查询不覆盖正常的 CSS?

Why don't media queries override normal CSS?

我是否需要将 !important 添加到我为网站编写的媒体查询中的所有属性,如下例所示?

我的样式表底部有下面的 CSS,但我发现这些属性在我添加 !important 标签之前并没有反映我的设计。我知道使用 !important 标签不是最佳做法。

CSS

.loginbar {
    padding: 20px;
}
.logo {
    display: inline-block;
}

@media screen and (max-width: 1042px) {
        .loginbar {
            padding: 10px !important;
        }
        .logo {
            diplay: none !important;
        }
    }

HTML

    <div class=".logo"></div>
    <div class="loginbar"><a href="#">Log In | Sign Up</a></div>

理论上,不需要 - 您不需要 !important 标志。您可能遇到的问题来自 specificity

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors

Mozzila

特异性背后的基础数学(大大简化)是一种加权方法。

id 值 100, class 值 10, tag 值 1。

因此 a.class (tag + class = 11) 不如 a#id (tag + id = 101).

CSS 也以 last-match-wins 格式应用,也就是说将应用最后声明的匹配的选择器的样式(根据上述特异性排序)。

所以 - 在您的示例中,您的页面上可能有一些元素带有 class .element,这些元素是针对更具体的选择器(例如 .container div > ul li + li .element (这比 .element 更具体)所以它的样式将覆盖您的媒体样式的样式。

对此的警告是,如果正在使用 !important 标志。在这种情况下,覆盖样式的唯一方法是再次提供 !important 标志。