Container Queries: The Component Holy Grail
The biggest CSS breakthrough in 15 years. Instead of asking how wide the global browser window is, components can now inspect their immediate parent container, allowing one single card component to thrive anywhere in your design system!
1. The Problem: The Sidebar Card Nightmare
Suppose you are on a 1920px widescreen monitor. Your page has a narrow 280px sidebar. If you put a card in that sidebar, the media query sees 1920px and says: "Great, render wide desktop layout with 3 horizontal columns!". The card is crushed to death and overflows the sidebar!
With container queries, the card doesn't care what device the user is holding. It asks its parent box:"Do I have 400px of space right here?" If yes, expand horizontally. If placed in a 280px sidebar, stack vertically. True component independence!
2. The 2-Step Implementation Recipe
3. Interactive Studio: Drag to Resize the Parent Container
Smart Responsive Widget
Wide container unlocked! Avatar and text sit side by side.
4. Deep Visualizer: Container Query Interactive Lab
Container Queries
Simulate a component that changes style based on its container width.
Try these
- Increase the min width and note when the style flips.
- Compare to viewport media queries: this is parent-sized.
- Use container-type and @container together to scope styles.
Container queries react to parent size, not viewport. Use container-type and @container rules.
.card {
container-type: inline-size;
}
@container (min-width: 320px) {
.card { background: #fbbf24; }
}<div class="card">Resize parent; above 320px, container query applies.</div>
First-Year Student Traps: Container Queries
- 1.Always use
inline-size, notsize:container-type: sizerequires the browser to calculate both width AND height upfront. If your container doesn't have an explicit height, it collapses to 0px!container-type: inline-sizelooks only at width and is what you want in 99% of web apps. - 2.A container cannot style itself via @container: An element with
container-typecannot query itself inside@container(to prevent infinite layout recursion loops). Only its children can query it!
Accessibility in CSS (WCAG, Focus, High Contrast)
Master :focus-visible, accessible color contrast ratios (4.5:1), and screen-reader .sr-only patterns.