@media 讓樣式依輸出裝置(螢幕、列印、語音等)與特性(寬度、解析度、色深、長寬比)條件化套用,是響應式網頁設計(RWD)的基石。
@media [邏輯關鍵字] [媒體類型] and (媒體特性) {
/* 條件符合時套用的樣式 */
}
only(防舊瀏覽器誤讀)、not(否定)、and(串接多特性)、,(或邏輯,等同多條 @media)。screen(螢幕)、print(列印)、all(全部)、speech(語音)。width/min-width/max-width、height、orientation、resolution、aspect-ratio、color、prefers-color-scheme、prefers-reduced-motion 等。/* 基礎樣式(行動裝置) */
.container { padding: 1rem; }
/* 平板以上 */
@media (min-width: 768px) {
.container { padding: 2rem; }
}
/* 桌機以上 */
@media (min-width: 1024px) {
.container { max-width: 1200px; margin: 0 auto; }
}
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
.hero { background-image: url(hero@2x.jpg); }
}
@media (prefers-color-scheme: dark) {
:root { --bg: #121212; --text: #e0e0e0; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
@media (aspect-ratio: 16/9) {
.video-wrapper { height: 56.25vw; }
}
min-width 遞增斷點,減少覆寫。熟練媒體查詢,能讓網站在千變萬化的裝置環境中保持一致的優質體驗。