nshunz
nshunz

Reputation: 263

Media query properties being overwriiten by other breakpoints

I need to apply a few styles depending on the width of the viewport. To do this I wrote a few media queries but on running them I found that the smaller media queries are being overwritten.

Code sample: https://codepen.io/anon/pen/joLVGZ

HTML

<div>
  hello
</div>

CSS

div {
  height: 200px;
}
/*
 * Less than 576px
*/
@media screen and (max-width: 576px) {
  div {
    background-color: red;
  }
}

/*
 * Less than 768px
 */
@media screen and (max-width: 768px) {
  div {
    background-color: green;
  }
}

/*
 * Less than 992px 
*/
@media screen and (max-width: 992px) {
  div {
    background-color: blue;
  }
}

/*
 * Less than 1200px
*/
@media screen and (max-width: 1200px) {
  div {
    background-color: yellow;
  }
}

/*
Greator than 1200px
*/
@media (min-width: 1200px) {
  div {
    background-color: grey;
  }
}

In the sample I tried changing the browser size but the background color set at 992px (Yellow) overwrites the other breakpoints and the color remains yellow for all other smaller size.

How do I make sure styles do not overwrite other styles? Are my media queries written wrongly?

Upvotes: 0

Views: 379

Answers (2)

G3ck
G3ck

Reputation: 252

Just change the order of @media:

div {
  height: 200px
}
/* More than 1200px */
@media (min-width: 1200px) {
  div {
    background-color: grey;
  }
}

/* Less than 1200px */
@media screen and (max-width: 1200px) {
  div {
    background-color: yellow;
  }
}
/* Less than 992px */
@media screen and (max-width: 992px) { 
  div {
    background-color: blue;
  }
}
/* Less than 768px */
@media screen and (max-width: 768px) {
  div {
    background-color: green;
  }
}
/* Less than 576px */
@media screen and (max-width: 576px) {
  div {
    background-color: red;
  }
}

Upvotes: 1

Johannes
Johannes

Reputation: 67758

Just reverse the order of your media queries. The way you have them, the second-to-last one overwrites all previous ones, since max-width: 1200px applies to everything below 1200px.

Upvotes: 1

Related Questions