问题
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.
回答1:
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;
}
回答2:
Because the id is important.
Right way:
media="all"
#mainmenu {
display:inline-block;
}
@media screen and (max-width: 760px)
#mainmenu {
display:none;
}
来源:https://stackoverflow.com/questions/15361205/media-query-being-overridden-by-previous-rule