網頁排版時,考慮不同終端設備瀏覽大小是很重要的一環 解析度過小造成跑版,過大時把一些區塊size寫死又會造成頁面太空曠 RWD(Responsive web design) 的第一步,便從這開始
CSS 的媒體查詢 (Media Requires) 語法
1
2
3
@ media ( query ) {
/* CSS Rules used when query matches */
}
Copy
可以查詢的項目很多,不過 RWD 最常用的是 min-width
、max-width
、min-height
和 max-height
。
min-width
:任何超過查詢中指定寬度的瀏覽器都會套用規則。
max-width
:任何未超過查詢中指定寬度的瀏覽器都會套用規則。
min-height
:任何超過查詢中指定高度的瀏覽器都會套用規則。
max-height
:任何未超過查詢中指定高度的瀏覽器都會套用規則。
有涉獵過的人應該也知道還有 device-width
這個東西,但是 device-width
是針測裝置的螢幕的大小,而非檢視區的大小,通常只用在行動裝置上,建議還是以上面列舉的四項屬性為主。
下面列舉三種不同大小,更換不同背景顏色:
1
2
3
@ media ( min-height : 1024px ) and ( min-height : 768px ) { body { background-color : red ; } } /* 1024 x 768 */
@ media ( min-height : 1440px ) and ( min-height : 900px ) { body { background-color : blue ; } } /* 1440 x 900 */
@ media ( min-height : 1920px ) and ( min-height : 1080px ) { body { background-color : green ; } } /* 1920 x 1080 */
Copy
也可以在 link tag 的 media attribute 寫入規則,來引入不同的樣式表
1
2
3
< link media = "(max-width: 1024px)" href = "max-1024px.css" rel = "stylesheet" />
< link media = "(max-width: 1440px)" href = "max-1440px.css" rel = "stylesheet" />
< link media = "(max-width: 1920px)" href = "max-1920px.css" rel = "stylesheet" />
Copy
這裡有一些可以參考的例子::http://mediaqueri.es/
References: