How to lock viewport to Portrait Orientation in HTML5/CSS3

As my experience, it cannot be done as you are access the website from the browser. Which should have the lock orientation capability is the browser itself - e.g Safari, Chrome. Your HTML CSS code will not be feasible to control it.

For example when you are building a hybrid mobile app - meaning an application with html css and js then convert it to mobile app with wrapper as a web view inside. Then you are capable to lock the screen orientation. There are some configuration need to be done and later on these will be converted to Objective C or Java.


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.

Note that this will not actually lock the orientation, just make the page look like it is locked.