響應式佈局由 Ethan Marcotte 2010 年提出:一個網站兼容多終端,而非為每終端做專版。隨移動互聯網盛行,成為大勢所趨。本文詳解概念、優缺點、Media Queries 實現全流程。

| 優點 | 缺點 |
|---|---|
| 面對不同分辨率靈活性強 快速解決多設備適配 | 兼容工作量大、效率低 代碼冗餘、隱藏元素增加加載時間 屬折衷方案、難達最佳 改變原有結構易致用戶混淆 |
@media 和 @import 規則、HTML/XML 中均可用。邏輯關鍵字:only(限定設備)、and(邏輯與)、not(排除)。多設備用逗號分隔。
device-width、device-heightwidth、heightorientation: portrait | landscapeaspect-ratio、device-aspect-ratiocolor、color-indexresolution


<link rel="stylesheet" media="only screen and (max-width: 480px), only screen and (max-device-width: 480px)" href="link.css" />
@media (min-device-width: 1024px) and (max-width: 989px),
screen and (max-device-width: 480px),
(max-device-width: 480px) and (orientation: landscape),
(min-device-width: 480px) and (max-device-width: 1024px) and (orientation: portrait) {
/* rules */
}
/* 視口 < 980px */
@media screen and (max-width: 980px) {
#wrap {width: 90%; margin: 0 auto;}
#content {width: 60%; padding: 5%;}
#sidebar {width: 30%;}
#footer {padding: 8% 5%; margin-bottom: 10px;}
}
/* 視口 < 650px */
@media screen and (max-width: 650px) {
#header {height: auto;}
#searchform {position: absolute; top: 5px; right: 0;}
#content {width: auto; float: none; margin: 20px 0;}
#sidebar {width: 100%; float: none; margin: 0;}
}
/* 禁用 iPhone Safari 字號自動調整 */
html { -webkit-text-size-adjust: none; }
/* HTML5 元素塊級化 */
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; }
/* 圖片/視頻自適應 */
img { max-width: 100%; height: auto; width: auto\9; /* IE8 */ }
.video embed, .video object, .video iframe { width: 100%; height: auto; }
頁面 <head> 必加:
<meta name="viewport" content="width=device-width; initial-scale=1.0">
viewport 控制移動端原始大小顯示與縮放:width、height、initial-scale、minimum-scale、maximum-scale。
推薦 Responsivator:輸入 URL(含本地 https://127.0.0.1/)即可模擬 iPhone 等多設備顯示效果,支援自定義尺寸。