萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 媒體查詢判斷 iPad 橫豎屏:Orientation 實戰

純 CSS 方案:@media orientation

<style media="all and (orientation: portrait)">
  /* 豎屏樣式 */
  #landscape { display: none; }
  body { background: red; }
</style>

<style media="all and (orientation: landscape)">
  /* 橫屏樣式 */
  #portrait { display: none; }
  body { background: green; }
</style>

也可合併在單一 CSS:

@media (orientation: portrait)  { #landscape { display: none; } body { background: red; } }
@media (orientation: landscape) { #portrait  { display: none; } body { background: green; } }

支援範圍

  • iOS Safari 4+、Android Browser 2.3+、Chrome、Firefox、Edge、IE10+ 全支援。
  • 桌面瀏覽器視窗寬高比決定 orientation (寬>高 = landscape)。

進階:結合裝置寬度精準控制

/* iPad 豎屏 (768px) */
@media (orientation: portrait) and (max-width: 768px) { ... }

/* iPad 橫屏 (1024px) */
@media (orientation: landscape) and (max-width: 1024px) { ... }

/* iPad Pro 12.9" */
@media (orientation: portrait) and (max-width: 1024px) { ... }
@media (orientation: landscape) and (max-width: 1366px) { ... }

JavaScript 監聽補充 (動態切換類別)

window.addEventListener('orientationchange', () => {
  document.body.dataset.orientation = window.orientation === 0 ? 'portrait' : 'landscape';
});
/* CSS */
body[data-orientation="portrait"]  .landscape-only { display: none; }
body[data-orientation="landscape"] .portrait-only  { display: none; }

解決 `orientationchange` 事件延遲、縮放導致判斷不準等問題。

最佳實踐

  1. 優先用 **流式布局 + Flex/Grid** 自然適配,減少橫豎屏專用代碼。
  2. 僅在**必須**鎖定佈局 (如遊戲、全屏圖表、攝影頭預覽) 時使用 orientation 查詢。
  3. 配合 `viewport-fit=cover` (iPhone X+ 刘海屏) 處理安全區域:`padding: env(safe-area-inset-top) env(safe-area-inset-right) ...`。
copyright © 萬盛學電腦網 all rights reserved