CSS How to Use Media Query for Orientation
@media (orientation: portrait) or @media (orientation: landscape) to apply styles depending on the device's orientation.Examples
How to Think About It
@media blocks with orientation: portrait or orientation: landscape to apply styles only in those cases.Algorithm
Code
@media (orientation: portrait) {
body {
background-color: lightblue;
}
}
@media (orientation: landscape) {
body {
background-color: lightgreen;
}
}Dry Run
Let's trace how the background color changes with device orientation.
Check orientation
Device is held tall, so orientation is portrait.
Apply portrait styles
Background color changes to lightblue.
Change orientation
Device is rotated to wide, orientation is landscape.
Apply landscape styles
Background color changes to lightgreen.
| Step | Orientation | Background Color |
|---|---|---|
| 1 | portrait | lightblue |
| 4 | landscape | lightgreen |
Why This Works
Step 1: Orientation media feature
The orientation media feature detects if the device is in portrait or landscape mode.
Step 2: Conditional styling
Using @media (orientation: portrait) applies styles only when the device is tall.
Step 3: Automatic updates
When the device rotates, the browser automatically applies the correct styles inside the matching media query.
Alternative Approaches
window.addEventListener('resize', () => { if(window.innerHeight > window.innerWidth) { document.body.style.backgroundColor = 'lightblue'; } else { document.body.style.backgroundColor = 'lightgreen'; } });
@media (min-aspect-ratio: 1/1) { body { background-color: lightgreen; } } @media (max-aspect-ratio: 1/1) { body { background-color: lightblue; } }
Complexity: O(1) time, O(1) space
Time Complexity
Media queries are evaluated by the browser instantly on orientation change, so the time cost is constant.
Space Complexity
No extra memory is needed beyond the CSS rules defined, so space complexity is constant.
Which Approach is Fastest?
CSS media queries are faster and more efficient than JavaScript detection because they are handled natively by the browser.
| Approach | Time | Space | Best For |
|---|---|---|---|
| CSS orientation media query | O(1) | O(1) | Simple, efficient style changes on orientation |
| JavaScript resize detection | O(1) per resize event | O(1) | Dynamic control but less efficient |
| Aspect-ratio media query | O(1) | O(1) | Alternative to orientation but less clear |
@media (orientation: portrait) to target tall screens and @media (orientation: landscape) for wide screens easily.