Container Queries thực chiến: Responsive components không cần media query
Container Queries cho phép component tự responsive theo kích thước parent, không phụ thuộc viewport. Đây là cách tiếp cận component-first thực sự cho CSS.
Bao nhiêu lần bạn viết một component card đẹp lung linh, rồi nhét vào sidebar thì nó vỡ layout? Media queries chỉ biết viewport width, không biết gì về container chứa component. Container Queries giải quyết đúng pain point này.
Vấn đề với media queries
Media queries responsive theo viewport — tức là theo màn hình người dùng. Nhưng trong thực tế, cùng một component có thể xuất hiện ở main content (rộng) lẫn sidebar (hẹp) trên cùng một viewport. Media queries không handle được case này.
Container Queries hoạt động thế nào
Ý tưởng đơn giản: thay vì hỏi "viewport rộng bao nhiêu?", component hỏi "parent container rộng bao nhiêu?". Để dùng, bạn cần 2 bước:
/* Bước 1: Khai báo containment trên parent */
.card-wrapper {
container-type: inline-size;
container-name: card;
}
/* Bước 2: Query theo container */
@container card (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 200px 1fr;
gap: 1.5rem;
}
}
@container card (max-width: 399px) {
.card {
display: flex;
flex-direction: column;
}
.card img {
aspect-ratio: 16/9;
object-fit: cover;
}
}
container-type: inline-size bật size containment theo chiều inline (thường là width). Bạn cũng có thể dùng container-type: size nếu muốn query cả height, nhưng hầu hết cases chỉ cần inline-size.
Container Query Units
Một feature ít người biết: Container Queries đi kèm các đơn vị mới — cqw, cqh, cqi, cqb. Chúng hoạt động tương tự vw/vh nhưng relative to container:
.card-title {
/* Font size = 5% chiều rộng container */
font-size: clamp(1rem, 5cqi, 2rem);
}
.card-image {
/* Responsive height theo container */
height: 30cqb;
}
Thực tế áp dụng
Mình đã dùng Container Queries trong design system của team và nhận ra vài điều:
- Component thực sự portable — cùng một ProductCard dùng ở homepage grid, sidebar, modal mà không cần variant props.
- Giảm CSS đáng kể — không cần viết media queries riêng cho mỗi layout context.
- Browser support tốt — tất cả modern browsers đã support từ 2023. Chỉ cần fallback cho IE (mà ai còn support IE?).
Khi nào dùng Container Queries vs Media Queries?
Container Queries: component-level responsive — cards, widgets, form fields, bất kỳ component nào cần adapt theo context.
Media Queries: page-level layout — grid columns, navigation pattern (hamburger vs horizontal), overall spacing.
Hai cái không thay thế nhau mà bổ sung cho nhau. Container Queries giúp bạn nghĩ theo hướng component-first, đúng tinh thần của React/Vue component architecture.
Kết
Nếu bạn đang build design system hoặc component library, Container Queries là must-have. Nó biến CSS responsive từ page-centric thành component-centric — đúng cách mà frontend hiện đại nên hoạt động.
Admin
Bình luận (0)
Đăng nhập để bình luận
Chưa có bình luận nào. Hãy là người đầu tiên!