Skip to content

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;
  }
}