UI Design: Applying CSS Based on Screen Orientation

With the introduction of CSS3 Media Queries, we are able to shift and apply CSS between different viewport or device screen sizes.

We can detect the viewport width threshold, which we want the style rules to be applied to, with the min-width or max-width declaration within the Media Queries, as we have shown in our Responsive Design Series.

Device Orientation

Mobile devices can be operated with two orientations, Portrait and Landscape. In particular cases, we might also need to apply these styles based on the devices orientation apart from the device viewport width. To serve different stylesheets based upon screen and orientation declaration in the stylesheet link:

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

This will apply the styles for iPad, iPhone, Android, Safari, and Firefox. Alternatively, we can also add the orientation declaration within the Media Queries, like so.

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

As W3C described, regardless of the device type (mobile or desktop), when the viewport height is larger than the width, the orientation is described as portrait. Conversely, it is described as landscape when the width viewport size is larger than the height.

Preview

Below are some of the test preview in iPhone, iPad and Desktop with Landscape and Protrait orientation.

iPhone (Portrait)

iPhone (Landscape)

iPad (Portrait)

iPad (Landscape)

Desktop (Portrait)

Desktop (Landscape)

You can see for yourselves the demo in action and download the source from the following links. Resize the browser window or turn your device screen to see different results as shown in the screenshots above.

Further Resource

0 nhận xét:

Đăng nhận xét