Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Thiết lập Media Queries cho các thiết bị khác nhau với CSS

Giới thiệu

Media Queries cho phép áp dụng CSS khác nhau tùy theo đặc điểm thiết bị: chiều rộng màn hình, orientation, resolution, prefers-color-scheme, v.v. Đây là nền tảng của Responsive Web Design.

Cú pháp cơ bản

@media <media-type> and (<media-feature>) {
  /* CSS rules */
}
  • Media type: screen, print, speech, all (mặc định)
  • Media feature: width, height, min-width, max-width, orientation, resolution, prefers-color-scheme, prefers-reduced-motion

Ví dụ: Thay đổi background theo chiều rộng màn hình

<!DOCTYPE html>
<html>
<head>
  <style>
    /* Mobile first: mặc định cho màn hình nhỏ */
    body {
      background-color: lightblue;
      padding: 1rem;
      font-family: system-ui, sans-serif;
    }
    
    /* Tablet: >= 768px */
    @media screen and (min-width: 768px) {
      body { background-color: lightgreen; }
    }
    
    /* Desktop: >= 1024px */
    @media screen and (min-width: 1024px) {
      body { background-color: lightpink; }
    }
    
    /* Large desktop: >= 1440px */
    @media screen and (min-width: 1440px) {
      body { background-color: lavender; }
    }
  </style>
</head>
<body>
  <p>Màn hình < 768px: xanh nhạt | 768-1023px: xanh lá | 1024-1439px: hồng | ≥ 1440px: oanh</p>
</body>
</html>

Breakpoint phổ biến (Mobile First)

TênMin-widthThiết bị điển hình
MobileMặc định (0)Phone portrait
Large Mobile480pxPhone landscape
Tablet768pxiPad portrait, tablet
Desktop1024pxLaptop, desktop nhỏ
Large Desktop1440pxMonitor rộng, 2K
4K/Ultra1920px4K, ultrawide

Media Features hiện đại quan trọng

/* Dark mode */
@media (prefers-color-scheme: dark) {
  :root { --bg: #1a1a1a; --text: #fafafa; }
}

/* Giảm chuyển động (accessibility) */
@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    transition-duration: 0.01ms !important;
  }
}

/* High contrast mode */
@media (prefers-contrast: high) {
  .btn { border: 2px solid currentColor; }
}

/* Hover capability (touch vs mouse) */
@media (hover: hover) and (pointer: fine) {
  .tooltip:hover::after { opacity: 1; }
}

/* Resolution (retina, high DPI) */
@media (min-resolution: 2dppx) {
  .logo { background-image: url(logo@2x.png); }
}

Best Practice

  • Mobile First: Viết CSS cho mobile trước, dùng min-width để scale up
  • Dùng em/rem cho breakpoint thay vì px (accessibility zoom)
  • Gom media queries theo component, không theo trang
  • Tránh quá nhiều breakpoint — 4-5 là đủ
  • Test trên thiết bị thật, không chỉ devtools