Search code examples
htmlcssmedia-queries

Media query in css not working for different width


I am learning media query at the moment.I am trying to give different width to the div as per the device width.This is the css i have done

.cont
{
  margin:auto;
  width:1200px;
  background-color:maroon;
  height:80px;

}

@media all and (max-width:480px)
{
  .cont{ width:400px; background-color:yellow; }
}

@media all and (max-width:768px)
{
  .cont{ width:700px; background-color:pink; }
}

I have included the meta tag as well

<meta name="viewport" content="width=device-width, initial-scale=1.0">

The problem here is that media query won't work for max-width:480.In the 480 and less resolution it still shows the background color of max-width:768px ie the pink color.
If i keep the max-width:480px query below max-width:768px then the 480px will work and 768px won't.How do i make both work?


Solution

  • add a min-width for 768 @media query

    demo - http://jsfiddle.net/41x65u8d/

    @media only screen and (max-width : 320px) {
        .cont {
            background:blue;
        }
    }
     @media only screen and (min-width : 321px) and (max-width : 768px) {
        .cont {
            background:pink;
        }
    }