DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> DIV十CSS布局 >> 布局實例
用純 CSS 判斷 iPad 的直向與橫向
編輯:布局實例     

iPad 直放與橫放時,版面需要的配置往往不同。這件事不必靠 JavaScript 偵測視窗寬高,用 CSS 媒體查詢的 orientation 條件就能搞定。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Link study</title>

<!-- 直向(豎版)使用的樣式 -->
<style media="all and (orientation:portrait)" type="text/css">
#landscape { display: none; }
body {background:red}
</style>

<!-- 橫向(橫版)使用的樣式 -->
<style media="all and (orientation:landscape)" type="text/css">
#portrait { display: none; }
body {background:green}
</style>

</head>
<body>
</body>
</html>

它是怎麼運作的

orientation:portrait 指的是高度大於或等於寬度的情況,也就是直式;orientation:landscape 則是寬度大於高度,也就是橫式。這兩個條件互斥且窮盡,任何時刻只會有一組樣式生效。

範例中,直向時隱藏 id 為 landscape 的元素、背景設紅;橫向時反過來隱藏 portrait、背景設綠。螢幕旋轉的瞬間樣式就自動切換,完全不需要重載頁面。

更實用的寫法

把兩個方向各自的樣式集中在同一份檔案裡,用@media 區隔,會比拆成兩個 style 標籤更好維護:

/* 共通樣式 */
.card { padding: 20px; }

@media screen and (orientation: portrait) {
  .card { width: 90%; }
  .sidebar { display: none; }
}

@media screen and (orientation: landscape) {
  .card { width: 60%; float: left; }
  .sidebar { display: block; width: 35%; float: right; }
}

要注意的是,orientation 判斷的是「視窗」的方向,不一定是裝置的方向。在桌機上把瀏覽器視窗拉成瘦高型,portrait 樣式同樣會被觸發。若你的目標是明確針對 iPad,搭配 max-width 一起寫會更精準,例如 @media screen and (max-width:1024px) and (orientation:portrait)。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved