CSS媒体特性 - 方向



CSS orientation 媒体特性用于确定设备屏幕或页面是处于纵向还是横向方向。

设备的方向并不总是与屏幕的方向相同。例如,如果您在纵向方向的设备上打开软键盘,屏幕将比高宽更宽。在这种情况下,浏览器将使用横向样式而不是纵向样式。

可能的值

  • portrait − 当视口的高度超过其宽度时应用此值,这通常表示设备垂直放置。

  • landscape − 当视口的宽度大于其高度时应用此值,这通常表示设备水平放置。

语法

orientation: portrait|landscape;

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

CSS orientation - portrait 值

以下示例演示了当设备处于portrait方向时,盒子的背景颜色会变为绿色:

Open Compiler
<html> <head> <style> iframe { display: block; height: 200px; } </style> </head> <body> <label id="labelWidth" for="width"></label> <input id="width" type="range" min="120" max="250" step="4" /> <iframe id="block" srcdoc="<style> @media (orientation: portrait) { div { background: lightgreen; } } </style><div><h3>To see the effect resize your viewport's width.</h3> <p>When box is in portrait orientation background changes to green color, otherwise background color will remain white.</p> </div>"> </iframe> <script> const updateSize = (size, label) => { block.style[size] = `${eval(size).value}px`; }; width.oninput = () => updateSize("width", labelWidth); </script> </body> </html>

CSS orientation - landscape 值

以下示例演示了当设备处于landscape方向时,盒子的背景颜色会变为黄色:

Open Compiler
<html> <head> <style> iframe { display: block; height: 200px; } </style> </head> <body> <label id="labelWidth" for="width"></label> <input id="width" type="range" min="120" max="250" step="4" /> <iframe id="block" srcdoc="<style> @media (orientation: landscape) { div { background: yellow; } } </style><div><h3>To see the effect resize your viewport's width.</h3> <p>When box is in portrait orientation background changes to yellow color, otherwise background color will remain white.</p> </div>"> </iframe> <script> const updateSize = (size, label) => { block.style[size] = `${eval(size).value}px`; }; width.oninput = () => updateSize("width", labelWidth); </script> </body> </html>
广告