媒体查询被以前的规则覆盖 [英] Media Query being overridden by previous rule
问题描述
我试图默认在宽度小于760px的屏幕中隐藏我的菜单。由于某种原因,我的 display:none
规则不生效。它被以前的规则覆盖,如下所示:
media =all
#mainmenu {
display:inline-block;
}
@media屏幕和(max-width:760px)
.btncontent {
display:none;
}
这也值得注意,我有一个按钮,jQuery显示菜单通过添加内联样式。上面的代码是在按钮之前,没有内联样式。
我确定我错过了一些非常简单的,但不知道什么。提前感谢。
编辑:我已经通过添加ID选择器到媒体查询解决了这个问题,但我打算留下这个问题,
code>和 .btncontent
同一个元素?如果是这样,那么原因是因为ID选择器比类选择器更具体。 @media
规则不以任何方式影响规则优先权;它们是对级联透明 ,所以样式分辨率就像包含 @media
规则不存在。在您的示例中,当媒体查询完成时,浏览器会看到这一点,这表明带有ID的规则应该优先:
#mainmenu {
display:inline-block;
}
.btncontent {
display:none;
}
根据您将ID选择器添加到第二条规则的方式,或提示特殊性,允许其按预期覆盖:
/ *更具体* /
#mainmenu.btncontent {
display:none;
}
/ *同样具体* /
#mainmenu,.btncontent {
display:none;
}
I'm trying to hide my menu by default in screens less than 760px wide. For some reason though, my display:none
rule is not taking effect. It's being overridden by a previous rule, as follows:
media="all"
#mainmenu {
display:inline-block;
}
@media screen and (max-width: 760px)
.btncontent {
display:none;
}
It's also worth noting that I have a button that jQuery reveals the menu by adding an inline style. The above code is before the button is pressed though, with no inline styles.
I'm sure I'm missing something really simple here but not sure what. Thanks in advance.
EDIT: I've solved this issue by adding the ID selector to the Media Query but I'm going to leave this question open as I don't really understand why it worked.
Are #mainmenu
and .btncontent
the same element? If so, then the reason is simply because the ID selector is more specific than the class selector.
@media
rules do not influence rule precedence in any way; they are transparent to the cascade, so style resolution takes place as if the enclosing @media
rule wasn't there. In your example, when the media query is fulfilled, browsers see this, which makes it clear that the rule with the ID should take precedence:
#mainmenu {
display:inline-block;
}
.btncontent {
display:none;
}
Depending on how you added the ID selector to the second rule, you either balance or tip the specificity, allowing it to override as expected:
/* More specific */
#mainmenu.btncontent {
display:none;
}
/* Equally specific */
#mainmenu, .btncontent {
display:none;
}
这篇关于媒体查询被以前的规则覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!