Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change viewport tag depending on device width?

Tags:

html

css

Regarding the viewport meta tag, I want to establish different viewports at different screen sizes.

  • By default, I want the viewport to be "width=1024"
  • At device widths of lower than 768px, I want the viewport to be "width=device-width,initial-scale=1"

The reason for this is that I want to set a non-fluid layout for tablets that scales when you flip them vertically, but I want a different set of layouts for mobile devices.

How can this be done?

like image 269
develdevil Avatar asked Sep 17 '25 22:09

develdevil


1 Answers

Using the link that cjspurg posted above as a starting point, I eventually came up with a method to reliably detect the screen width (in CSS pixels) and set the viewport accordingly:

<meta id="testViewport" name="viewport" content="width=1024">
<script>
var sw = screen.width;
var sh = screen.height;
if ( window.matchMedia("(orientation: landscape)").matches ) {
  var fw = sh;
} else {
  var fw = sw;
}
if (fw < 768) {
    var mvp = document.getElementById("testViewport");
    mvp.setAttribute("content","width=device-width,initial-scale=1");
}
</script>
like image 90
develdevil Avatar answered Sep 19 '25 12:09

develdevil