p3kr1s p3kr1s - 14 days ago 5
CSS Question

Using multiple @media (max-width) CSS

I am trying to make a responsive website, and am using

@media only screen and (max-width:...)
&
@media only screen and (min-width:...)
to try and size everything.

When using multiple
@media
on one
div
, it does not seem to work.

The fiddle here will explain what I am trying to do.

HTML

<div class="mainNavi2">
<p> test </p>
</div>


CSS

@media only screen and (max-width: 800px) {
.mainNavi2{
border:1px solid orange;
}
}

@media only screen and (min-width: 851) {
.mainNavi2{
border:1px solid green;
}
}

@media only screen and (max-width: 850) {
.mainNavi2{
border:1px solid blue;
}
}


What I am basically trying to do is:



  • when the screen is at 800px (or less), an orange border will be displayed

  • for width of 850px (or less) a blue border will be displayed

  • for a width of 851 (or more) a green border will be displayed.




They all work separately, but when all put together, only the
max-width:800px
works.

Answer

Because of the order of your media queries, the orange is being overridden by the blue. Rearrange them and it works:

@media only screen and (max-width: 850px) {
    .mainNavi2 {
        border:1px solid blue;
    }
}
@media only screen and (max-width: 800px) {
    .mainNavi2 {
        border:1px solid orange;
    }
}
@media only screen and (min-width: 851px) {
    .mainNavi2 {
        border:1px solid green;
    }
}

Demo

A better approach might be to follow Bootstrap's lead and go mobile-first, using only ascending min-width statements:

.mainNavi2 {
    border:1px solid orange;
}
@media only screen and (min-width: 801px) {
    .mainNavi2 {
        border:1px solid blue;
    }
}
@media only screen and (min-width: 851px) {
    .mainNavi2 {
        border:1px solid green;
    }
}

Demo 2

Comments