0

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
suryanaga
  • 3,728
  • 11
  • 36
  • 47

2 Answers2

3

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;
}
Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

Because the id is important.

Right way:

media="all"
#mainmenu {
       display:inline-block;
}

@media screen and (max-width: 760px)
#mainmenu {
         display:none;
}
Damonsson
  • 1,532
  • 14
  • 25
  • I don't understand why the element doesn't adhere to all rules which apply to it? – suryanaga Mar 12 '13 at 12:35
  • 1
    Because id(#) is important than class(.). No matter what you wrote will always be taken for id, this is just a rule of thumb. – Damonsson Mar 12 '13 at 12:41