Reputation: 57
Let's say for example I have:
@media(max-width:800px) {
/* Some Code */
}
@media(max-width:500px) {
/* Some Code */
}
The browser randomly chooses one of those, If I view on 800px, it might choose the 800px css or it might choose the 500px code. If I view on 500px, it might choose the 800px css or it might choose the 500px code. I've noticed, it uses 800px more often, even if my screen size is 500px or less. And sometimes, it combines the 2. Here is a screenshot of code the browser is picking up...
Notice how it's picking up on both widths, but then max-width:500px
was crossed off? My screen resolution was set to 500px in that. I would appreciate the help. Thank you.
Upvotes: 0
Views: 82
Reputation: 67758
Apparently (which becomes clear from your screenshot) the order of the media queries in your code is not as you posted it, but this way:
@media(max-width:500px) { /* rule for nav-item starts at line 26 */
/* Some Code */
}
@media(max-width:800px) { /* rule for nav-item starts at line 38 */
/* Some Code */
}
And this is the wrong order, since the 800px query will always apply to everything which before appied to the 500px query and overwrite it. (The order is important).
So just swap the order of those - 800px first, then 500px - and you be will all set.
Upvotes: 1
Reputation: 5511
The selector with the highest specificity will always apply. Any unexpected behaviour will be due to something affecting specificity.
So this is definitely not random, though it may appear so to you for some reason.
With selectors with the same precedence such as the one in your example, the last one found will apply. Notice how it has the largest line number of all the found rules. The media query only affects when it will apply, and has no effect on its specificity.
Perhaps the order of your CSS is changing without you realising (a preprocessor behaving unexpectedly perhaps?), or you perhaps you are changing the order yourself without realising that affects specificity. Also note that rules could come from multiple rule sets, perhaps that is confusing you too? If what I talked about there doesn't seem to ring a bell, definitely read up on how cascading works.
As regards your example it's not exactly clear what you're trying to achieve and what the actual problem is but it is absolutely certain both media queries would match when at 500px wide. Seems likely you don't want that so therefore you just change your media queries:
@media (min-width: 501px) and (max-width:800px) {
/* Some Code */
}
@media (max-width:500px) {
/* Some Code */
}
Upvotes: 0