Home > database >  CSS @media queries only work in Device Mode of Developer Tools - React
CSS @media queries only work in Device Mode of Developer Tools - React

Time:04-19

So as the title describes, I've developed a responsive web app using React framework with several @media queries; When I resize the page with the Device Mode of Developer Tools, queries work absolutely fine and everything behave as they should, but when I resize the actual browser window, media queries don't work. I even tried changing screen resolution and the issue still was there.

These are my @media queries :

@media only screen and (max-device-width: 768px) {...}

@media only screen and (max-device-width: 768px) and (min-device-width: 691px) {...}

@media only screen and (max-device-width: 768px) and (min-device-width: 576px) {...}

@media only screen and (max-device-width: 939px) and (min-device-width: 769px) {...}

@media only screen and (min-device-width: 940px) {...}

@media only screen and (min-device-width: 1024px) {...}

@media only screen and (min-device-width: 1200px) {...}

@media only screen and (min-device-width: 1510px) {...}

It may seem a little bit messy but because of some situations I had to mix the min and max criteria, and it works on Device Mode totally fine.

And the HTML viewport meta tag:

<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />

I also tried changing or removing viewport meta tag but still no chance.

What could be the problem ?!

CodePudding user response:

device-width has been deprecated and is likely the reason why you're not seeing the change on your desktop device since current browsers don't support it. Change your queries to just max or min -width

https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-width

Here's an example. You'll see that the first @media with device width never actually kicks on (the light blue) but the red one does https://jsfiddle.net/astombaugh/bceg3nts/5/

body {
  background-color: yellow;
}

@media only screen and (max-device-width: 600px) {
  body {
    background-color: lightblue;
  }
}


@media only screen and (max-width: 650px) {
  body {
    background-color: red;
  }
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />
</head>
<body>

<h1>The @media Rule</h1>

<p>Resize the browser window. When the width of this document is 600 pixels or less, the background-color is "lightblue", otherwise it is "yellow".</p>

</body>
</html>

  • Related