標籤:
在 CSS2 中,你可以為不同的媒介裝置(如螢幕、印表機)指定專用的樣式表,而現在藉助 CSS3 的 Media Queries 特性,可以更為有效實現這個功能。你可以為媒介類型添加某些條件,檢測裝置並採用不同的樣式表。
例如,你可以把用於大螢幕上顯示的樣式和用於行動裝置的專用樣式放在一個樣式文檔中,這樣,在不改變文檔內容的情況下,不同的裝置可以呈現不同的介面外觀。閱讀這篇文章學習 CSS3 Media Queries 的準系統和國外使用 CSS3 的 Media Queries 特性的優秀網站案例。
Max Width
下面的樣式會在可視地區的寬度小於 600px 的時候被應用。
| 12345 |
@media screen and (max-width: 600px) { .class { background: #ccc; }} |
如果你想連結到一個單獨的樣式表,把下面的代碼放在<head>標籤裡。
| 1 |
<link rel="stylesheet" media="screen and (max-width: 600px)" href="small.css" /> |
Min Width
下面的樣式會在可視地區的寬度大於 900px 的時候被應用。
| 12345 |
@media screen and (min-width: 900px) { .class { background: #666; }} |
Multiple Media Queries
你還可以使用過個匹配條件,下面的樣式會在可視地區的寬度在 600px 和 900px 之間的時候被應用。
| 12345 |
@media screen and (min-width: 600px) and (max-width: 900px) { .class { background: #333; }} |
Device Width
下面的樣式會在 max-device-width 是 480px 的裝置上觸發。(提示:max-device-width 是裝置的實際解析度,而 max-width 指的是可視地區解析度。)
| 12345 |
@media screen and (max-device-width: 480px) { .class { background: #000; }} |
For iPhone 4
下面的樣式是為 iPhone 4 專門寫的 (作者: Thomas Maier)。
| 1 |
<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" type="text/css" href="iphone4.css" /> |
For iPad
你還可以使用 media query 在 iPad 上檢測方向(portrait or landscapse) (作者: Cloud Four)。
| 12 |
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css"><link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css"> |
CSS3 Media Queries 實現響應式設計