CSS Orientation Queries

What You Learn From This Page

  • How portrait and landscape media queries compare viewport width and height.
  • Why CSS orientation is not the same as physical device orientation.
  • When orientation is useful and when width or container queries are more accurate.
  • How to combine orientation with width and height conditions safely.
  • How short landscape screens affect heroes, dialogs, navigation, forms, and controls.
  • How to build shape-dependent layouts for video, games, dashboards, and reading apps.
  • How orientation changes affect accessibility, focus, scrolling, and essential functionality.
  • How to test rotation, resizing, mobile keyboards, square viewports, and dynamic states.

Introduction

CSS orientation queries apply styles according to the shape of the viewport. A viewport is landscape when it is wider than it is tall. It is portrait when its height is greater than or equal to its width. The browser evaluates that relationship and updates matching rules when the viewport changes through rotation, window resizing, split-screen mode, browser controls, or other environmental changes.

The feature is simple, but it is often misused as device detection. Landscape does not mean desktop, and portrait does not mean phone. A rotated phone can be wide but extremely short, while a narrow desktop window can be tall and portrait-shaped. Most standard layout decisions depend on available width, not on the ratio between width and height.

Orientation becomes valuable when viewport shape itself affects the experience: a full-screen game places controls beside the play area in landscape, a video interface uses the short vertical dimension differently, or an immersive dashboard changes axes. The strongest implementation combines orientation with width or height where necessary and keeps one flexible, accessible experience in both states.

Basic Orientation Query Syntax

The orientation media feature accepts two values: portrait and landscape. Each condition surrounds ordinary CSS rules.

@media (orientation: portrait) {
  .feature {
    flex-direction: column;
  }
}

@media (orientation: landscape) {
  .feature {
    flex-direction: row;
  }
}

The syntax does not ask whether a hardware sensor reports rotation. It asks whether the current media viewport satisfies the relevant dimensional relationship.

What Portrait Means

Portrait matches when viewport height is greater than or equal to viewport width. A 390 by 844 viewport is portrait because it is taller than it is wide. A square 800 by 800 viewport is also portrait because equality belongs to the portrait condition.

@media (orientation: portrait) {
  .gallery {
    grid-template-columns: 1fr;
  }
}

One column may work in this example, but width itself might be a better reason for that choice. A very wide portrait viewport could support several columns.

What Landscape Means

Landscape matches when viewport width is strictly greater than viewport height. An 844 by 390 viewport is landscape, as is a 1440 by 900 desktop window. The large difference in usable space between those examples is why orientation alone cannot define a desktop layout.

@media (orientation: landscape) {
  .media-controls {
    padding-inline: 2rem;
  }
}

This rule is reasonable when the control bar can use horizontal space without assuming the viewport has room for several major page columns.

Orientation Describes the Viewport

A desktop browser can switch from landscape to portrait when the user resizes its window from a broad rectangle to a narrow, tall shape. No device physically rotates. Similarly, split-screen and embedded web views can change the viewport ratio independently of the outer display.

This distinction should shape every query decision. Write orientation rules for a shape-dependent layout effect, not as a substitute for detecting phones, tablets, or desktops.

Physical Rotation Often Changes the Query

On phones and tablets, physical rotation commonly changes the viewport dimensions, so the orientation query reevaluates automatically. CSS can update the layout without a JavaScript resize listener or manual class toggling.

The relationship is indirect. Browser UI, application chrome, multitasking modes, and platform policies determine the final viewport. Test the actual supported environments instead of assuming sensor position maps perfectly to CSS orientation.

A Square Viewport Is Portrait

Orientation is binary; there is no square value. When width and height are equal, (orientation: portrait) matches. This boundary matters when automated tests use square screenshots or a resizable panel passes through equal dimensions.

Do not write mutually exclusive application logic that assumes every portrait viewport is taller by a meaningful amount. A nearly square view may need the same flexible behavior as either neighboring state.

Orientation vs Width Queries

An orientation query answers whether width is greater than height. A width query answers whether a known amount of horizontal space is available. For navigation, sidebars, form columns, and most card layouts, the second question directly represents the requirement.

@media (min-width: 60rem) {
  .layout {
    grid-template-columns: 16rem minmax(0, 1fr);
  }
}

If this layout works in wide portrait and landscape viewports alike, adding an orientation condition would unnecessarily exclude valid space.

Combine Orientation with Width

When shape and minimum horizontal space both matter, require both conditions.

@media
  (orientation: landscape)
  and (min-width: 60rem) {
  .dashboard {
    grid-template-columns: 16rem minmax(0, 1fr);
  }
}

This prevents a small rotated phone from receiving a multi-column workstation layout merely because it is landscape. Every condition should contribute a real constraint rather than approximate a device category.

Combine Orientation with Height

Short landscape screens are one of the best reasons to use orientation. The design may need less vertical padding, natural section height, or a bounded scroller.

@media
  (orientation: landscape)
  and (max-height: 35rem) {
  .hero {
    min-height: auto;
    padding-block: 1.5rem;
  }
}

The rule describes the actual problem: a landscape shape with constrained height. A normal desktop landscape viewport does not receive the compact vertical treatment.

The Small Landscape Phone Problem

A phone viewport around 667 by 375 is landscape but has limited width after browser controls, safe areas, and page gutters. It has even less height. A desktop navigation, persistent sidebar, large hero, and several fixed controls can consume the complete view.

Treat small landscape as a distinct constraint only where necessary. Let ordinary content flow, reduce nonessential vertical space, keep primary controls reachable, and avoid adding columns that make each region unusably narrow.

Mobile Browser Controls Affect Height

Mobile browser bars can expand or collapse while the user scrolls, changing visible space. Classic viewport units may represent different concepts depending on the browser, while modern dvh, svh, and lvh provide dynamic, small, and large viewport interpretations.

An orientation query alone does not solve this variability. Use bounded dimensions, content flow, and tested dynamic viewport units when full-screen interfaces depend on height.

Software Keyboards Can Change Available Space

Focusing an input can reduce the visual viewport when an on-screen keyboard appears. Depending on platform behavior, the document viewport and orientation condition may not change exactly as expected. Fixed dialogs and bottom controls can become hidden even though the orientation query still matches.

Input-heavy pages should avoid relying on orientation as their only signal. Keep focused controls scrollable into view, use flexible heights, and test forms with the keyboard open in both portrait and landscape.

Orientation vs Container Queries

Orientation describes the viewport. A reusable component may receive a narrow container in a landscape viewport or a wide container in a portrait viewport. Container queries are more accurate when the component's allocated width drives the layout.

.card-region {
  container-type: inline-size;
}

@container (min-width: 30rem) {
  .card {
    grid-template-columns: 10rem minmax(0, 1fr);
  }
}

Reserve orientation for relationships connected to the overall viewport shape, not as a general replacement for component responsiveness.

Prefer Intrinsic Grid for Card Counts

A gallery or card collection usually needs to fit as many useful columns as available width permits. Intrinsic Grid expresses this without assigning a fixed count to portrait and landscape.

.gallery {
  display: grid;
  grid-template-columns: repeat(
    auto-fit,
    minmax(min(100%, 12rem), 1fr)
  );
  gap: 1rem;
}

A tablet in portrait may fit more cards than a small phone in landscape. Available container width, not orientation label, should decide.

Prefer Flexbox for Simple Direction Changes

A feature block can begin in a content-safe column and use a width threshold when side-by-side presentation becomes useful.

.feature {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

@media (min-width: 48rem) {
  .feature {
    flex-direction: row;
    align-items: center;
  }
}

Add (orientation: landscape) only if the side-by-side relationship is specifically unsuitable for a wide portrait context. The fewer assumptions a query contains, the more environments it handles correctly.

Full-Screen Applications Are a Strong Use Case

Games, camera interfaces, presentation tools, media players, and immersive dashboards often use the entire viewport. Its shape determines where controls and content can coexist, so orientation becomes meaningful.

.app-shell {
  min-height: 100dvh;
  display: grid;
  grid-template-rows: minmax(0, 1fr) auto;
}

@media (orientation: landscape) {
  .app-shell {
    grid-template-columns: minmax(0, 1fr) 18rem;
    grid-template-rows: 1fr;
  }
}

The source order should remain logical in both arrangements, and each region needs appropriate minimums and overflow behavior.

Game Interface Pattern

A game can place controls beneath the play area in portrait and beside it in landscape. This is a direct response to viewport shape rather than a device guess.

.game {
  display: grid;
  gap: 1rem;
  grid-template-rows: minmax(0, 1fr) auto;
}

@media (orientation: landscape) {
  .game {
    grid-template-columns: minmax(0, 1fr) auto;
    grid-template-rows: 1fr;
  }
}

Controls must remain large enough for touch, keyboard access must remain coherent, and the play region should not push controls outside the short viewport.

Video Interface Pattern

A full-screen player may place a playlist below video in portrait and beside it in sufficiently wide landscape.

.video-layout {
  display: grid;
  grid-template-rows: auto minmax(0, 1fr);
}

@media
  (orientation: landscape)
  and (min-width: 50rem) {
  .video-layout {
    grid-template-columns: minmax(0, 1fr) 18rem;
    grid-template-rows: 1fr;
  }
}

The width condition prevents an undersized video and crowded playlist on a small phone. Native video controls and captions must remain reachable in either layout.

Dashboard Pattern

A full-height dashboard can stack navigation over content by default and use a rail in a wide landscape state.

.dashboard {
  min-height: 100dvh;
  display: grid;
  grid-template-rows: auto minmax(0, 1fr);
}

@media
  (orientation: landscape)
  and (min-width: 60rem) {
  .dashboard {
    grid-template-columns: 16rem minmax(0, 1fr);
    grid-template-rows: 1fr;
  }
}

Metric cards inside the main region should use intrinsic or container-aware layouts rather than inheriting the page's orientation logic.

Reading Application Pattern

Reading content should preserve a comfortable line length in both orientations. A sufficiently wide landscape view can add navigation without stretching prose.

.reader {
  max-inline-size: 65ch;
  margin-inline: auto;
}

@media
  (orientation: landscape)
  and (min-width: 70rem) {
  .reader-layout {
    display: grid;
    grid-template-columns: 14rem minmax(0, 65ch);
    justify-content: center;
    gap: 2rem;
  }
}

The content measure remains stable; extra room improves navigation rather than producing excessively long lines.

Hero Sections on Short Landscape Screens

A full-viewport hero can dominate a landscape phone because vertical space is scarce. Use a bounded minimum and a short-height override instead of forcing every hero to occupy exactly one viewport.

.hero {
  min-block-size: min(42rem, 80dvh);
  padding: clamp(1.5rem, 5vw, 4rem);
}

@media
  (orientation: landscape)
  and (height < 35rem) {
  .hero {
    min-block-size: auto;
    padding-block: 1.5rem;
  }
}

Ensure the next section remains discoverable and that text never overlaps media or actions as the height changes.

Dialogs on Short Landscape Screens

Fixed-height dialogs can place actions outside the viewport. Constrain the panel and provide intentional internal scrolling.

.dialog {
  inline-size: min(90vw, 36rem);
  max-block-size: 90dvh;
  overflow: auto;
}

@media
  (orientation: landscape)
  and (height < 35rem) {
  .dialog {
    inline-size: min(80vw, 44rem);
  }
}

Keep the dialog heading and close control reachable, preserve focus containment if modal, and test with the software keyboard open.

Navigation Should Usually Follow Width

A portrait query can suggest reduced horizontal space, but it does not prove persistent links will not fit. A landscape phone can still be too narrow for them. Measure the actual labels and use a width threshold for compact versus expanded navigation.

Orientation may adjust spacing inside a full-screen application header, but it should not be the sole definition of mobile and desktop navigation modes.

Forms Should Usually Follow Available Width

Whether form fields can sit side by side depends on their usable width, labels, hints, and error messages. A width or container query directly models that requirement.

.form-row { display: grid; gap: 1rem; }

@media (min-width: 45rem) {
  .form-row {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

Orientation can supplement a height adjustment for keyboard-heavy forms, but it should not determine the field grid by itself.

Image Composition and Aspect Ratio

CSS can alter an image container's aspect ratio according to viewport shape.

.hero-image {
  aspect-ratio: 4 / 5;
  object-fit: cover;
}

@media (orientation: landscape) {
  .hero-image { aspect-ratio: 16 / 9; }
}

Cropping must not remove important information. Informational screenshots and diagrams often need contain or natural dimensions rather than decorative cover cropping.

Use picture for Art Direction

If the actual composition must change, the picture element can offer orientation-specific image sources.

<picture>
  <source
    media="(orientation: portrait)"
    srcset="hero-portrait.webp">
  <img
    src="hero-landscape.webp"
    width="1400"
    height="800"
    alt="Team reviewing a project dashboard">
</picture>

Both sources should communicate the same meaning because they share alternative text. Provide intrinsic dimensions and optimize each resource for its likely rendered size.

Orientation and Fluid Values

Use fluid typography and spacing for continuous change, then add an orientation-height query only where a short viewport requires a specific correction.

.presentation {
  padding: clamp(1.5rem, 5vw, 5rem);
}

@media
  (orientation: landscape)
  and (height < 32rem) {
  .presentation {
    padding-block: 1rem;
  }
}

This avoids maintaining separate portrait and landscape values for every property while still protecting the constrained case.

Compose Orientation with Logical Operators

Use and when every condition must match. A comma-separated query list means OR and should be used carefully.

@media
  (orientation: landscape)
  and (width >= 50rem)
  and (height < 40rem) {
  .workspace { gap: 1rem; }
}

@media
  (orientation: portrait),
  (width < 40rem) {
  .toolbar { flex-wrap: wrap; }
}

In the second example, every portrait viewport matches regardless of width. Confirm that the same wrapping decision makes sense for both alternatives.

Orientation and Print Are Separate Concerns

Print output may itself be portrait or landscape, but browser print layout also involves page size, margins, pagination, and @page rules. A screen orientation strategy should not be assumed to produce a useful PDF.

Use @media print to restore natural heights, remove interactive controls, expose useful links, and prevent clipped regions. Test both portrait and landscape print settings through actual preview.

Use CSS Instead of Resize Scripts for Styling

Do not attach a resize listener merely to toggle classes for simple orientation styling. Media queries update efficiently and keep presentation in CSS. JavaScript resize handlers can fire frequently, duplicate breakpoint logic, and create timing problems.

Use script only when behavior or application state genuinely depends on the condition. Even then, prefer matchMedia() over repeatedly comparing dimensions.

Observe Orientation in JavaScript When Necessary

The same condition can be observed through window.matchMedia() for behavior that CSS cannot provide.

const landscape = window.matchMedia(
  '(orientation: landscape)'
);

function handleOrientation(event) {
  console.log(event.matches ? 'landscape' : 'portrait');
}

handleOrientation(landscape);
landscape.addEventListener('change', handleOrientation);

Do not use this to rearrange DOM content that CSS can place more safely. Keep semantic order stable and ensure behavior remains correct if the condition changes while an interaction is active.

Preserve Functionality in Both Orientations

Users must still be able to navigate, submit forms, read content, reach actions, dismiss dialogs, and recover from errors after rotation. Orientation should adapt presentation rather than remove capability.

A hidden control may remain focused, a drawer can stay open in an invalid mode, or a fixed footer can cover content after rotation. Define state transitions and responsive ownership so the interface remains coherent as queries reevaluate.

Do Not Force Rotation for Ordinary Websites

A message that requires users to rotate their device creates an unnecessary barrier for people with mounted devices, limited mobility, locked orientation, or a strong preference. Normal websites should support both shapes.

Specialized games, simulations, or camera experiences may have a genuine orientation requirement. Explain the reason, keep critical controls available, and provide the best fallback possible rather than presenting a blank page.

Protect Source and Focus Order

Grid placement and Flexbox direction can make regions appear in different locations without changing DOM order. If the visual sequence changes meaningfully, keyboard focus and assistive-technology reading may no longer align with what sighted users see.

Keep a logical source order that works in both orientations. Use orientation to change tracks and axes while preserving the task sequence. Test keyboard traversal immediately after rotating or resizing.

Manage Scroll Position and Sticky Elements

Rotation can change line wrapping and section heights, so the browser may preserve a scroll offset that now points somewhere unexpected. Sticky headers and sidebars can also consume a much larger proportion of a short landscape viewport.

Keep sticky regions bounded, avoid stacking several fixed bars, and verify that headings and focused controls are not hidden. Do not reset scroll position on every orientation change unless the product has a strong task-specific reason.

Account for Safe Areas in Full-Screen Layouts

Phones and tablets can have display cutouts, rounded corners, and system gesture regions. Their relationship to the interface changes during rotation, so controls positioned safely in portrait may move too close to an edge in landscape. Full-screen media, games, and camera interfaces should combine ordinary padding with safe-area environment values.

.full-screen-controls {
  padding-block:
    max(1rem, env(safe-area-inset-top))
    max(1rem, env(safe-area-inset-bottom));
  padding-inline:
    max(1rem, env(safe-area-inset-left))
    max(1rem, env(safe-area-inset-right));
}

The values can change as the device rotates. Keep essential actions away from obstructed or gesture-sensitive edges without assuming which physical side contains a cutout. Test on devices or emulation that exposes safe-area insets, and verify that added padding does not leave an already short landscape viewport unusable.

Handle Transitions During Rotation Carefully

When a query changes Grid tracks, flex direction, dimensions, and positioning at once, existing transitions may animate through awkward intermediate states. Content can slide across the screen, controls can briefly overlap, and a large layout movement can be uncomfortable for users who prefer reduced motion.

Do not add transition: all to responsive containers. Transition only properties whose interpolation is intentional, and allow structural orientation changes to occur immediately when that produces a clearer result. Respect prefers-reduced-motion for any remaining animation.

@media (prefers-reduced-motion: reduce) {
  .app-shell,
  .media-controls {
    transition: none;
  }
}

Rotate while a drawer, dialog, or playback overlay is open. The interface should settle into its new arrangement without losing focus, resetting progress, or leaving a transition frozen between modes.

Common Misinterpretations

Landscape is not desktop, portrait is not mobile, and CSS orientation is not a hardware sensor. A wide display can host a portrait window, a phone can be landscape, and a square viewport is portrait. These facts make orientation unsuitable as the sole signal for most navigation and column decisions.

Ask what the layout actually needs: a minimum width, a maximum height, a component container, an input capability, or the viewport ratio itself. Query that condition directly.

Avoid Excessive Orientation Overrides

Two large blocks containing dozens of portrait and landscape overrides create separate designs that must remain synchronized. Small changes can leave one orientation incomplete, and source-order interactions become difficult to track.

Build one flexible base with intrinsic sizing and normal flow. Add a few orientation-specific rules only for relationships that depend on shape. Keep them near the component or application shell that owns the behavior.

Debugging Orientation Queries

If a query does not appear to match, inspect the viewport dimensions reported by developer tools and confirm whether width is actually greater than height. Browser chrome, emulation settings, and device pixel ratio do not change the basic CSS-pixel relationship, but they can make visual assumptions misleading.

If the condition matches but the style does not appear, inspect cascade layers, specificity, source order, and invalid declarations. A matching media query does not automatically override a stronger rule.

Test Dynamic Rotation

Load the page in portrait, rotate to landscape, and rotate back without refreshing. Look for horizontal overflow, clipped dialogs, stale menu state, hidden focus, incorrect scroll containers, overlapping fixed controls, and lost application state. CSS queries reevaluate automatically, but scripts and component state may not.

Repeat while a menu, modal, video, form, or game control is active. Transitions between states are often more revealing than separate screenshots taken after a clean load.

Test a Matrix of Shapes and Sizes

Include narrow portrait, wide portrait, small landscape, tablet landscape, large desktop landscape, short desktop windows, and nearly square viewports. Test just on both sides of equality to confirm the intended square boundary.

Add zoom, larger text, localization, browser toolbars, safe areas, and on-screen keyboards. A query is useful only if its resulting layout survives realistic content and interaction conditions.

Orientation Query Reference

QueryMeaningTypical Use
(orientation: portrait)Height is at least widthShape-dependent vertical arrangement
(orientation: landscape)Width is greater than heightShape-dependent horizontal arrangement
(orientation: landscape) and (min-width: 60rem)Wide landscape viewportLarge application shell
(orientation: landscape) and (max-height: 35rem)Short landscape viewportHero or dialog height correction
(min-width: 48rem)Known horizontal roomNavigation, forms, and sidebars
@container (min-width: 30rem)Local component roomReusable cards and widgets

Choosing the Better Signal

RequirementBetter Signal
A sidebar has enough spaceViewport or container width
Navigation labels fit one rowWidth based on real labels
Card column countIntrinsic Grid or container width
Form fields fit side by sideContainer width
Full-screen game control placementOrientation
Short landscape heroOrientation plus height
Video and playlist arrangementOrientation plus minimum width
Reusable component layoutContainer query
Touch target sizingPointer capability

Common Mistakes and Better Approaches

MistakeBetter Approach
Landscape means desktopRequire the width the layout needs
Portrait means phoneTreat orientation as viewport shape only
Sidebar controlled only by orientationUse a content-based width threshold
Card counts assigned by orientationUse intrinsic Grid
Large fixed landscape heroCombine orientation with height
Fixed-height dialogBound height and allow local scrolling
Important content hidden in portraitAdapt presentation while preserving access
Separate designs with many overridesUse one flexible base and focused changes
Resize JavaScript for stylingUse CSS media queries
Testing only static screenshotsRotate dynamically during active states

Common Interview Questions

What is an orientation media query? It conditionally applies CSS according to whether the viewport is portrait or landscape.

When is a viewport landscape? Landscape matches when viewport width is greater than viewport height.

When is a viewport portrait? Portrait matches when height is greater than or equal to width, including a square viewport.

Is CSS orientation based directly on physical rotation? No. It is based on current viewport dimensions, although rotating a device commonly changes those dimensions.

Should orientation replace width breakpoints? Usually not. Width more directly answers whether standard page regions and controls fit.

When are orientation queries especially useful? Full-screen games, video players, camera interfaces, presentations, and short landscape layouts where viewport shape affects composition.

Why combine orientation with height? It isolates short landscape viewports without applying compact vertical rules to large desktop landscape screens.

How should reusable components respond? Prefer intrinsic sizing or container queries because their local space may not correspond to viewport orientation.

Practical Review Checklist

  • Use orientation only when viewport shape genuinely affects the layout.
  • Remember that equal width and height count as portrait.
  • Do not treat landscape as desktop or portrait as mobile.
  • Prefer width conditions for navigation, forms, and sidebars.
  • Prefer container queries for reusable component layouts.
  • Use intrinsic Grid and Flexbox before assigning counts by orientation.
  • Combine orientation with width or height when the constraint requires both.
  • Account for browser controls, dynamic viewport height, and software keyboards.
  • Keep dialogs and controls reachable on short landscape screens.
  • Preserve essential content and functionality in both orientations.
  • Keep semantic, reading, and focus order coherent after rearrangement.
  • Avoid maintaining two large sets of orientation overrides.
  • Use CSS for presentation and matchMedia() only for necessary behavior.
  • Test rotation in both directions without refreshing the page.
  • Test narrow, wide, short, square, zoomed, and localized states.

Key Takeaway

Orientation queries compare viewport dimensions: portrait means height is greater than or equal to width, while landscape means width is greater than height. They describe shape, not device type or physical sensor state. That makes them powerful for full-screen, immersive, and height-constrained interfaces but too broad for many ordinary responsive decisions.

Use width or container queries when the amount of horizontal space is the real requirement. Use orientation when the relationship between width and height genuinely changes the composition, and combine it with minimum width or maximum height when necessary. Build one flexible, accessible baseline, preserve complete functionality through rotation, and test dynamic transitions rather than assuming portrait and landscape screenshots tell the whole story.