David Davó
David Davó

Reputation: 690

CSS media queries ignores order of preference

It's simple, I have a CSS that should apply to <body>, but doesn't apply.

@media only screen
  and (min-device-width: 320px) 
  and (max-device-width: 600px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: portrait){
    body{
        margin-left: 5px;
        margin-right: 5px;
    }
}

body {
    margin: 0 0 0 0;
    background-color: #212121;
}

Is in the order that I used.

Upvotes: 0

Views: 300

Answers (2)

Sasank Mukkamala
Sasank Mukkamala

Reputation: 1574

Your CSS is actually getting applied correctly.

In CSS, if two rules have the same origin, weight and specificity, then the one declared last overrides the previous one. So in your case, margin-left: 5px; and margin-right: 5px; are getting applied but they are immediately getting overridden by margin: 0 0 0 0;.

So all you have to do is change the order. Like this:

body {
    margin: 0 0 0 0;
    background-color: #212121;
}
@media only screen
  and (min-device-width: 320px) 
  and (max-device-width: 600px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: portrait){
    body{
        margin-left: 5px;
        margin-right: 5px;
    }
}

Upvotes: 1

SG_Rowin
SG_Rowin

Reputation: 622

Nothing is wrong with your code, its just your ordering. In a responsive web design, you should use "mobile-first" CSS. this means that your media queries should be AFTER your default css:

body {
margin: 0 0 0 0;
background-color: #212121;
}

  @media only screen
  and (min-device-width: 320px) 
  and (max-device-width: 600px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: portrait){
    body{
    margin-left: 5px;
    margin-right: 5px;

    }
}

Upvotes: 0

Related Questions