<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; } }
/* 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) { ... }
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` 事件延遲、縮放導致判斷不準等問題。