Quy tắc @media trong CSS dùng để chỉ định các style khác nhau cho các loại media khác nhau (print, screen, all, v.v.) trong một stylesheet duy nhất. Thường đi kèm danh sách media type phân cách bằng dấu phẩy và khối khai báo CSS chứa quy tắc style cho media đích.
Cú pháp
@media not | only mediatype and (expressions) {
CSS-Code;
}
Media Types phổ biến
screen — Màn hình máy tính, điện thoại, tablet
print — Máy in, xem trước in
speech — Trình đọc màn hình
all — Tất cả (mặc định)
Media Features (Điều kiện)
| Feature | Mô tả |
width / min-width / max-width | Chiều rộng viewport |
height / min-height / max-height | Chiều cao viewport |
orientation | portrait hoặc landscape |
resolution | Độ phân giải (dpi, dppx) |
hover | Có hỗ trợ hover không (hover, none) |
prefers-color-scheme | light, dark, no-preference |
prefers-reduced-motion | reduce, no-preference |
Ví dụ 1: Responsive grid cột
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* { box-sizing: border-box; }
.col {
float: left;
width: 20%;
padding: 40px;
background: #333;
color: white;
text-align: center;
}
body { background-color: lemonchiffon; margin: 20px; }
@media screen and (max-width: 850px) {
.col { width: 50%; }
body { background-color: mediumseagreen; }
}
@media screen and (max-width: 550px) {
.col { width: 100%; }
body { background-color: powderblue; }
}
</style>
</head>
<body>
<div class="row">
<div class="col">Col 1</div>
<div class="col">Col 2</div>
<div class="col">Col 3</div>
<div class="col">Col 4</div>
<div class="col">Col 5</div>
</div>
</body>
</html>
Ví dụ 2: Thay đổi background theo breakpoint
@media screen and (max-width: 900px) {
p {
background: url("image1.jpg");
color: #c303c3;
}
}
@media screen and (max-width: 500px) {
p {
color: black;
background: url("image2.jpg");
}
}
Best Practice Responsive
- Mobile-first: Viết CSS cho mobile trước, dùng
min-width để mở rộng
- Breakpoint chuẩn: 480px, 768px, 1024px, 1200px (hoặc theo content)
- Dùng rem/em cho breakpoint:
@media (min-width: 48rem)
- Container Queries (CSS mới):
@container (min-width: 400px) — responsive theo container cha
/* Mobile-first example */
.container { padding: 1rem; }
@media (min-width: 48rem) { .container { padding: 2rem; } }
@media (min-width: 64rem) { .container { padding: 3rem; } }