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

Responsive Web Design với Media Queries trong CSS

Media Queries cho phép áp dụng CSS khác nhau cho các điều kiện thiết bị (chiều rộng, chiều cao, orientation, resolution...).

Ví dụ mã nguồn: Đổi màu nền theo breakpoint

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
  body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; color: white; }
  
  /* Mobile first - mặc định */
  body { background: rgb(207, 60, 151); }
  
  /* Tablet */
  @media only screen and (min-width: 600px) {
    body { background: rgb(0, 128, 107); }
  }
  
  /* Tablet large / Small laptop */
  @media only screen and (min-width: 768px) {
    body { background: rgb(226, 136, 18); }
  }
  
  /* Desktop */
  @media only screen and (min-width: 992px) {
    body { background: rgb(108, 25, 185); }
  }
  
  /* Large desktop */
  @media only screen and (min-width: 1200px) {
    body { background: rgb(13, 124, 63); }
  }
</style>
</head>
<body>
<h1>Media Queries Example</h1>
<h2>Resize màn hình để thấy màu nền thay đổi tại các breakpoint</h2>
</body>
</html>

Cú pháp Media Query


@media [not|only] mediatype and (media feature) { CSS }
/* mediatype: screen, print, speech, all */
/* media feature: width, height, orientation, resolution, hover, pointer... */

Media Features thường dùng

FeatureMô tảVí dụ
width / min-width / max-widthChiều rộng viewport@media (max-width: 768px)
height / min-height / max-heightChiều cao viewport@media (min-height: 800px)
orientationportrait | landscape@media (orientation: landscape)
resolution / min-resolutionĐộ phân giải (dpi, dppx)@media (min-resolution: 2dppx) /* Retina */
hoverhover | none@media (hover: hover) { .tooltip:hover... }
pointerfine | coarse | none@media (pointer: coarse) { button { padding: 20px; } }
prefers-color-schemelight | dark | no-preference@media (prefers-color-scheme: dark) { body{background:#111} }
prefers-reduced-motionreduce | no-preference@media (prefers-reduced-motion: reduce) { *{animation:none} }

Mobile First vs Desktop First

  • Mobile First (Khuyến nghị): CSS mặc định cho mobile, dùng min-width để enhance lên. Ít code hơn, performance tốt hơn.
  • Desktop First: CSS mặc định desktop, dùng max-width để override xuống. Dễ hiểu nhưng code nhiều hơn.

Best Practices

  • Dùng em hoặc rem cho breakpoint (ví dụ: 48em = 768px @ 16px base) để respect user font-size setting
  • Gom breakpoint chung trong project (design system)
  • Tránh quá nhiều breakpoint phức tạp
  • Test trên thiết bị thật, không chỉ resize trình duyệt