Thiết kế web hiển thị tốt trên mọi thiết bị (mobile, tablet, desktop) là yêu cầu bắt buộc. Media Queries cho phép áp dụng CSS chỉ khi thỏa mãn điều kiện (kích thước màn hình, orientation...).
Responsive Web Design Và Media Queries
Responsive design: tối ưu stylesheet cho nhiều thiết bị/kích thước màn hình. Thiết bị và viewport ảnh hưởng đến hiển thị. Media queries là công cụ then chốt.
Media queries điều chỉnh style theo: loại thiết bị, orientation (portrait/landscape), viewport size.
Cú Pháp Media Query
@media media-type and (media-rule) {
/* CSS styles */
}
@media: Khai báo media querymedia-type:screen,print,speech,all(mặc định)and: Toán tử logic kết hợp type và rulemedia-rule: Điều kiện kích hoạt (width, height, orientation...)CSS styles: Quy tắc áp dụng khi điều kiện true
Các Loại Media Rules Phổ Biến
Width và Height
Áp dụng style khi viewport đúng kích thước:
@media screen and (width: 500px) { p { color: blue; } }
Thường dùng range với min-width, max-width, min-height, max-height:
@media screen and (min-width: 500px) { p { color: blue; } }
Áp dụng khi viewport ≥ 500px.
Orientation
Áp dụng theo hướng thiết bị:
@media (orientation: landscape) { h2 { font-size: 20px; } }
Desktop mặc định landscape.
Ví Dụ Thực Hành
1. Ẩn Phần Tử Trên Mobile
Hộp "This site is in beta" chỉ hiện trên mobile (viewport < 600px).
<p class="betaBox">This site is in beta.</p>
.betaBox { background-color: orange; padding: 10px; }
@media screen and (max-width: 600px) {
.betaBox { display: none; }
}

Mobile (<600px): display: none ẩn hộp. Desktop: hộp hiện bình thường.
2. Đa Media Queries: Font Size Theo Kích Thước
Đổi font-size <h1> theo 3 breakpoint:
- ≤ 480px: 16px
- 481px - 600px: 20px
- ≥ 601px: 24px
@media screen and (max-width: 480px) { h1 { font-size: 16px; } }
@media screen and (min-width: 481px) and (max-width: 600px) { h1 { font-size: 20px; } }
@media screen and (min-width: 601px) { h1 { font-size: 24px; } }

Media Query Breakpoints - Điểm Ngắt Phổ Biến
Breakpoints: điểm kích hoạt media query. Không có chuẩn cố định, nhưng tham khảo:
- Điện thoại:
@media screen and (max-width: 600px) - Tablet dọc/Điện thoại lớn:
@media screen and (min-width: 600px) - Tablet ngang:
@media screen and (min-width: 768px) - Laptop/Desktop:
@media screen and (min-width: 992px) - Màn hình lớn:
@media screen and (min-width: 1200px)
Cách tốt nhất: test web, tìm nơi bố cục bị vỡ, thêm breakpoint tại đó.
Kết Luận
Media queries cho phép áp dụng CSS có điều kiện (viewport, orientation...). Cơ sở của responsive design. Bạn đã sẵn sàng viết media queries như web designer chuyên nghiệp!