Blocking device rotation on mobile web pages

Viewed 160530

Is it possible to detect on my page, for example using Javascript, when user visit it using mobile device in portrait mode, and stop orientation changing when user rotate its phone to landscape? There is game on my page, optimized for portrait display only and I don't want it in landscape.

9 Answers

#rotate-device {
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: 9999;
    top: 0;
    left: 0;
    background-color: #000;
    background-image: url(/path to img/rotate.png);
    background-size: 100px 100px;
    background-position: center;
    background-repeat: no-repeat;
    display: none;
}

@media only screen and (max-device-width: 667px) and (min-device-width: 320px) and (orientation: landscape){
 #rotate-device {
  display: block;
 }
}
<div id="rotate-device"></div>

This solution worked for me, which just rotates the entire page 90 degrees when it's in landscape (effectively locking the screen in portrait). I couldn't go with some of the other options here, because I needed to support Safari.

@media screen and (min-width: 320px) and (max-width: 767px) and (orientation: landscape) {
  html {
    transform: rotate(-90deg);
    transform-origin: left top;
    width: 100vh;
    overflow-x: hidden;
    position: absolute;
    top: 100%;
    left: 0;
  }
}

Found it here: https://css-tricks.com/snippets/css/orientation-lock/

Related