Media Queries 是響應式設計的基石,讓你能依據裝置特性套用不同的樣式。以下從可用屬性、關鍵字到實作範例,一次梳理清楚。
常見的查詢屬性與其對應值如下:
屬性 值 Min/Max 說明
color integer yes 每種色彩的位元組數
color-index integer yes 色彩表中的色彩數
device-aspect-ratio integer/integer yes 裝置螢幕的寬高比
device-height length yes 裝置螢幕的輸出高度
device-width length yes 裝置螢幕的輸出寬度
grid integer no 是否為基於格柵的裝置
height length yes 渲染介面的高度
monochrome integer yes 單色緩衝區中每像素的位元組數
resolution resolution yes 解析度
scan - no TV 媒體類型的掃描方式
width length yes 渲染介面的寬度
orientation portrait/landscape no 橫屏或豎屏
組裝查詢條件時,常用到以下三個關鍵字:
可透過 link 標籤的 media 屬性,為不同裝置載入對應的樣式表:
<link rel="stylesheet" media="all" href="style.css" />
<link rel="stylesheet" media="screen and (min-width:980px)" href="desktop.css" />
<link rel="stylesheet" media="screen and (min-width:768px) and (max-width:980px)" href="pad.css" />
<link rel="stylesheet" media="screen and (min-width:480px) and (max-width:768px)" href="phone.css" />
<link rel="stylesheet" media="screen and (max-width:320px)" href="small.css" />
也可以在樣式表內部以 @media 撰寫條件:
@media screen and (min-width: 980px) { /* CSS */ }
@media screen and (min-width:768px) and (max-width:980px) { /* CSS */ }
@media screen and (min-width:480px) and (max-width:768px) { /* CSS */ }
@media screen and (max-width:320px) { /* CSS */ }
/* 裝置寬度等於 480px */
@media screen and (max-device-width: 480px) { /* CSS */ }
/* 裝置寬高比 */
@media screen and (device-aspect-ratio: 16/9),
screen and (device-aspect-ratio: 16/10) { /* CSS */ }
/* 豎屏 */
@media all and (orientation: portrait) { /* CSS */ }
/* 橫屏 */
@media all and (orientation: landscape) { /* CSS */ }
由於舊版 IE 不支援 Media Queries,可借助 jQuery 外掛來補足相容性:
https://archive.plugins.jquery.com/project/MediaQueries
實際動手縮放瀏覽器視窗,就能直接觀察到不同斷點下的樣式變化。