Skip to content

RWD 媒體查詢 media query:依裝置條件套用樣式

RWD 媒體查詢 media query:依裝置條件套用樣式

媒體查詢是 CSS3 的一個強大功能,讓我們能夠根據裝置的特性(如螢幕尺寸、解析度、方向等)來套用不同的樣式規則。

基本語法

css
@media 媒體類型 and (條件) {
  /* CSS 規則 */
}

媒體類型

全部媒體類型 (預設)

css
@media all {
  body { font-family: Arial, sans-serif; }
}

螢幕

css
@media screen {
  .container { max-width: 1200px; }
}

列印

css
@media print {
  .no-print { display: none; }
  body { color: black; background: white; }
}

媒體條件

寬度

精確寬度

css
@media (width: 768px) {
  .exact-width { color: red; }
}

最小寬度

css
@media (min-width: 768px) {
  .min-width { font-size: 18px; }
}

最大寬度

css
@media (max-width: 767px) {
  .max-width { font-size: 14px; }
}

寬度範圍

css
@media (min-width: 768px) and (max-width: 1024px) {
  .width-range { padding: 20px; }
}

高度

最小高度

css
@media (min-height: 600px) {
  .tall-screen { 
    padding-top: 50px; 
  }
}

最大高度

css
@media (max-height: 500px) {
  .short-screen { 
    padding: 10px; 
  }
}

螢幕方向

橫向

css
@media (orientation: landscape) {
  .landscape-only {
    display: block;
  }
}

縱向

css
@media (orientation: portrait) {
  .portrait-only {
    display: block;
  }
}

解析度

標準解析度

css
@media (resolution: 96dpi) {
  .standard-res { }
}

高解析度

css
@media (min-resolution: 192dpi) {
  .high-res {
    background-image: url('image@2x.jpg');
    background-size: 100px 100px;
  }
}

使用設備像素比

css
@media (-webkit-min-device-pixel-ratio: 2) {
  .retina-display { }
}

色彩能力

支援彩色

css
@media (color) {
  .color-support {
    background: linear-gradient(45deg, red, blue);
  }
}

最小色彩位元數

css
@media (min-color: 8) {
  .rich-color { }
}

單色螢幕

css
@media (monochrome) {
  .mono-screen {
    filter: grayscale(100%);
  }
}

邏輯運算子

and 運算子

同時滿足多個條件。

css
@media screen and (min-width: 768px) and (max-width: 1024px) {
  .tablet-landscape {
    grid-template-columns: repeat(2, 1fr);
  }
}

or 運算子

滿足任一條件。

css
@media (max-width: 768px), (orientation: portrait) {
  .mobile-or-portrait {
    flex-direction: column;
  }
}

not 運算子

不滿足條件時。

css
@media not screen {
  .not-screen {
    font-family: serif;
  }
}

@media not (min-width: 768px) {
  .not-desktop {
    font-size: 14px;
  }
}

行動優先的寫法

css
/* 預設:小螢幕 */
.card-list { display: grid; gap: 16px; }

/* 逐步增強 */
@media (min-width: 768px) {
  .card-list { grid-template-columns: repeat(2, 1fr); }
}

@media (min-width: 1200px) {
  .card-list { grid-template-columns: repeat(3, 1fr); }
}

min-widthmax-width 混用最容易讓斷點互相打架,整站統一一種方向即可。

偏好設定相關的查詢

css
@media (prefers-color-scheme: dark) { ... }
@media (prefers-reduced-motion: reduce) { ... }

有時候不必寫媒體查詢

css
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}

格線 的自動換欄、彈性盒子 的換行,都能讓版面自行適應。

常見問題

min-width 和 max-width 該用哪個?

行動優先就用 min-width,先寫小螢幕樣式再逐步增強;桌機優先則用 max-width。兩者混用最容易讓斷點互相打架,建議整站統一。

斷點的數值要照哪個裝置?

照內容,不照機型。裝置尺寸年年在變,跟著版面撐不住的位置設斷點才不會過時。

媒體查詢只能判斷寬度嗎?

不只。也能判斷方向、解析度、指標裝置的精準度,還能讀取使用者的偏好設定,例如:深色模式與降低動態效果。

有辦法不寫媒體查詢就響應嗎?

很多情況可以。格線的自動換欄、彈性盒子的換行,以及夾在最小與最大值之間的尺寸函式,都能讓版面自行適應。

延伸閱讀