The CSS Way: How to block UI only in landscape mode & in mobile?

Overview

Have you ever found any website irritating in landscape mode?

I have been in a situation that I don’t want users to navigate my web application in landscape mode because of any reason (I do have my reasons).

Things to do

1. Add an element with the appropriate message in your HTML.

  <div class="block-ui__wrapper">
    <p>Please change to portrait mode to further access our application</p>
  </div>

2. Spread that element to the whole viewport

Once you add the block element, fix it to the viewport and block the whole screen. Style it as per your brand guidelines and make sure that it is not visible by default.


  .block-ui__wrapper {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99999;
    display: none;
    /*
    Change colors accordingly
    */
    background: #000;
    color: #fff;
  }

3. Target the landscape view

Now is the time to display the hidden element in landscape view. Below is the code for the same. Further, used Flexbox just to center align the inner content to the viewport.


  @media (max-width: 767px)
   and (-webkit-min-device-pixel-ratio: 2)
   and (orientation: landscape) {
     .block-ui__wrapper {
         display: block;
         /*
         However, here is some extra snacks for you.
         To align everything in center.
         */
         display: -webkit-box;
         display: -webkit-flex;
         display: -moz-box;
         display: -ms-flexbox;
         display: flex;
         -webkit-box-pack: center;
         -webkit-justify-content: center;
            -moz-box-pack: center;
             -ms-flex-pack: center;
                 justify-content: center;
         -webkit-box-align: center;
         -webkit-align-items: center;
            -moz-box-align: center;
             -ms-flex-align: center;
                 align-items: center;
     }
   }

4. Prevent the scrolling

Wrap all the content (HTML elements) into one. Target and give the styling like in the below example. This will prevent the scrolling in both the mobile devices and screen-based devices.


  @media (max-width: 767px)
    and (-webkit-min-device-pixel-ratio: 2)
    and (orientation: landscape) {
      .full-content__wrapper {
        overflow: hidden;
        position: fixed;
        height: 100%;
        width: 100%;
      }
  }

Complete source code here.

Result

Block UI only in landscape mode

Conclusion

Pretty simple solution with CSS. Supports on smartphones and other screen-based devices.

Source code

← Back to all posts

up