Giới thiệu
Responsive Web Design (RWD) là phương pháp thiết kế web tự động điều chỉnh layout, hình ảnh, typography để hiển thị tối ưu trên mọi thiết bị: desktop, tablet, mobile. Ba trụ cột chính:
- Fluid Grid: Layout dựa trên % / fr / flex / grid (không fixed px)
- Flexible Images:
max-width: 100%; height: auto;— ảnh co giãn theo container - Media Queries: Thay đổi CSS tại các breakpoint
Ví dụ: Layout Responsive cơ bản
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* { box-sizing: border-box; }
.container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
padding: 1rem;
}
.row { display: flex; flex-wrap: wrap; gap: 1rem; margin: -0.5rem; }
.col { flex: 1 1 300px; padding: 0.5rem; background: #f0f0f0; }
/* Mobile first: 1 cột */
/* Tablet: 2 cột */
@media (min-width: 768px) {
.col { flex-basis: 45%; }
}
/* Desktop: 3-4 cột */
@media (min-width: 1024px) {
.col { flex-basis: 30%; }
}
img { max-width: 100%; height: auto; display: block; }
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col">Cột 1</div>
<div class="col">Cột 2</div>
<div class="col">Cột 3</div>
<div class="col">Cột 4</div>
</div>
</div>
</body>
</html>
Viewport Meta Tag (Bắt buộc)
<meta name="viewport" content="width=device-width, initial-scale=1.0">
width=device-width: Khớp viewport với chiều rộng thiết bịinitial-scale=1.0: Zoom mặc định 100%- Không dùng
user-scalable=no(vi phạm accessibility)
Responsive Images nâng cao
<!-- Art direction: ảnh khác nhau cho màn hình khác nhau -->
<picture>
<source media="(max-width: 480px)" srcset="hero-mobile.webp" type="image/webp">
<source media="(max-width: 1024px)" srcset="hero-tablet.webp" type="image/webp">
<img src="hero-desktop.webp" alt="Hero" loading="lazy">
</picture>
<!-- Resolution switching: cùng ảnh, kích thước khác -->
<img src="img-400w.jpg"
srcset="img-400w.jpg 400w, img-800w.jpg 800w, img-1200w.jpg 1200w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Responsive">
Modern CSS cho RWD (2023+)
/* Container Queries - style theo container cha, không viewport */
.card-container { container-type: inline-size; }
@container (min-width: 400px) {
.card { display: flex; }
}
/* CSS Grid auto-fit/auto-fill - không cần media query */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1rem;
}
/* Clamp() cho fluid typography/spacing */
:root { --space: clamp(0.5rem, 1vw, 1.5rem); }
Checklist RWD
- [ ] Viewport meta tag
- [ ] Box-sizing: border-box toàn cục
- [ ] Fluid grid (flex/grid/%/fr)
- [ ] Flexible images (max-width: 100%)
- [ ] Media queries mobile-first
- [ ] Touch targets ≥ 44×44px
- [ ] Font-size ≥ 16px (tránh zoom iOS)
- [ ] Test trên thiết bị thật + DevTools device toolbar