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
| Feature | Mô tả | Ví dụ |
|---|---|---|
| width / min-width / max-width | Chiều rộng viewport | @media (max-width: 768px) |
| height / min-height / max-height | Chiều cao viewport | @media (min-height: 800px) |
| orientation | portrait | landscape | @media (orientation: landscape) |
| resolution / min-resolution | Độ phân giải (dpi, dppx) | @media (min-resolution: 2dppx) /* Retina */ |
| hover | hover | none | @media (hover: hover) { .tooltip:hover... } |
| pointer | fine | coarse | none | @media (pointer: coarse) { button { padding: 20px; } } |
| prefers-color-scheme | light | dark | no-preference | @media (prefers-color-scheme: dark) { body{background:#111} } |
| prefers-reduced-motion | reduce | 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
emhoặcremcho 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