How to lock the vertical orientation of an application?

31 views Asked by At

I am using an application in Angular 14. How can I block the orientation change? I mean, I want the screen to be always displayed horizontally.

I have tried to do it this way, but it does not take the full width of the screen, keeps the width of the vertical. So the content stays in the middle of the screen. I also tried to add width: 100vw but it does not work.

@media only screen and (orientation:portrait) {
  body {
    height: 100vw;
    transform: rotate(90deg);
  }
}
1

There are 1 answers

1
Pasquale De Lucia On

I found three ways to look the device orintation

One method is to use native js enabling a full screeen view

// (A1) GO INTO FULL SCREEN FIRST
let de = document.documentElement;
if (de.requestFullscreen) { de.requestFullscreen(); }
else if (de.mozRequestFullScreen) { de.mozRequestFullScreen(); }
else if (de.webkitRequestFullscreen) { de.webkitRequestFullscreen(); }
else if (de.msRequestFullscreen) { de.msRequestFullscreen(); }

// (A2) THEN LOCK ORIENTATION
screen.orientation.lock('landscape');

Second method is use CSS

@media only screen and (orientation:portrait) {
  body {
    height: 100vw;
    transform: rotate(90deg);
  }
}

Third way is to alert the user to rotate the device

<!-- (A) THIS WILL SHOW ON THE WRONG ORIENTATION -->
<div id="turn">
  Please rotate your device!
</div>

<!-- (B) CONTENTS AS USUAL -->
<div id="container">
  Main contents here.
</div>

/* (A) WRONG ORIENTATION - SHOW MESSAGE HIDE CONTENT */
@media only screen and (orientation:landscape) {
  #turn { display:block; }
  #container { display:none; }
}
 
/* (B) CORRECT ORIENTATION - SHOW CONTENT HIDE MESSAGE */
@media only screen and (orientation:portrait) {
  #turn { display:none; }
  #container { display:block; }
}