Optimizing UI Design: How to Apply CSS Based on Screen Orientation

Thanks to CSS3 Media Queries, we can now easily adjust and apply CSS styles depending on the size of the device’s screen or viewport.

This article explores how to use min-width and max-width declarations within Media Queries to apply styles based on viewport dimensions. This is an extension of our Responsive Design Series.

Understanding Device Orientation

Mobile devices offer two orientations: Portrait and Landscape. Sometimes, you may need to apply styles based on the device’s orientation, in addition to its viewport width. Here’s how you can do it:

<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">

This method works across various platforms like iPad, iPhone, Android, Safari, and Firefox. You can also include the orientation declaration within Media Queries as shown below.

@media all and (orientation:portrait) {
  /* Styles for Portrait screen */
}
@media all and (orientation:landscape) {
  /* Styles for Landscape screen */
}

As defined by W3C, the orientation is considered portrait when the viewport height is greater than the width. Conversely, it’s landscape when the width is greater than the height.

Preview Examples

Here are some test previews on iPhone, iPad, and Desktop in both Landscape and Portrait orientations:

iPhone in Portrait Orientation
iPhone in Landscape Orientation
iPad in Portrait Orientation
iPad in Landscape Orientation
Desktop in Portrait Orientation
Desktop in Landscape Orientation

Feel free to check out the demo and download the source code to see these orientations in action.

Additional Resources

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail