How to lock viewport to Portrait Orientation in HTML5/CSS3

H. Ferrence picture H. Ferrence · Jul 13, 2016 · Viewed 22.3k times · Source

Is it possible to lock the view port's orientation to portrait on a mobile device?

I Googled it but could not find out exactly how to do it.

Answer

awe picture awe · Mar 8, 2019

This trick should work:

    @media screen and (orientation: landscape) {
      html {
        /* Rotate the content container */
        transform: rotate(-90deg);
        transform-origin: left top;
        /* Set content width to viewport height */
        width: 100vh;
        /* Set content height to viewport width */
        height: 100vw;
        overflow-x: hidden;
        position: absolute;
        top: 100%;
        left: 0;
      }
    }
<h1>Test</h1>

If you need this to only be applied on mobile devices, you can do some javascript tricks to identify the device type, and if a mobile device, you add a class is-mobile-device or something, and specify html.is-mobile-device as the selector in the style definition. You may already use a framework that adds classes for different device types already, so you can specify those.