Force Landscape Mode in a Mobile Web Game with CSS and JavaScript
This guide explains how to display a mobile web game exclusively in landscape orientation by rotating a container div with CSS transforms and JavaScript, avoiding intrusive prompts and handling devices with auto‑rotate enabled.
We need a landscape‑only view for a mobile web game. Prompting users to rotate their phones is poor UX, especially if auto‑rotate is disabled.
Existing APIs such as the Screen Orientation API and manifest settings do not meet the requirement.
The solution is to create a
divthat contains the game UI, and when the device is in portrait mode, rotate that
div90° with CSS transforms.
HTML structure: a container
#printthat holds the game canvas. In portrait mode we leave its width/height undefined; JavaScript measures the available screen width and height, determines orientation, and if portrait, sets the container’s dimensions and applies
transform: rotate(90deg).
CSS example for distinguishing orientation:
<code>@media (orientation: portrait) {
#print { /* no explicit size */ }
}
@media (orientation: landscape) {
#print { /* normal layout */ }
}
</code>JavaScript snippet:
var w = window.innerWidth, h = window.innerHeight;
if (w < h) { // portrait
var el = document.getElementById('print');
el.style.width = h + 'px';
el.style.height = w + 'px';
el.style.transform = 'rotate(90deg)';
}After applying the transform the game appears correctly in landscape even while the device is held vertically.
Note: If the device’s auto‑rotate lock is on, the screen may still flip unexpectedly. The fix is to detect the rotation lock state and optionally prompt the user or adjust the layout accordingly.
Images illustrate the original layout, the CSS rules, the JavaScript logic, and the before/after screenshots of portrait vs. landscape.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.