Container Queries
Style elements based on the size of their parent container, not the whole browser viewport, unlocking true component reusability.
What they are
Container Queries (@container) are conditional CSS rules, just like Media Queries. But instead of checking the width of the entire browser window, they check the width of a specific parent element (the container).
This is one of the most powerful modern CSS features, allowing components to govern their own layout independently of where they are placed on the page.
Why it matters
Imagine you build a beautiful 'Product Card' component. You want it to display horizontally (image left, text right) when there's plenty of space, and vertically (stacked) when space is tight.
If you use Media Queries, the card only knows about the browser window. If a user is on a massive desktop screen, but you place the card inside a narrow 300px sidebar, the media query sees the giant screen and applies the horizontal layout, breaking the card out of the sidebar!
Container queries solve this by letting the card ask: 'How much space do I actually have right here in this sidebar?'
How it works
1. **Define the Container**: First, you must tell the browser which parent element is the container. You do this by applying container-type: inline-size; to the parent wrapper.
2. **Query the Container**: Then, on the child elements, you write a query using @container (min-width: 400px) { ... }.
Now, regardless of the browser size, the styles will only apply if that specific parent wrapper is at least 400px wide.
Try it
Resize the parent container by dragging the handle. Watch how the card inside automatically adapts its layout from a vertical stack to a horizontal layout based on the space it has, completely ignoring the browser window size.
Container Resize
Container Width
Drag to resize the dashed container element.
Container is < 260px. Card stacks vertically.
Browser Window (Static)
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Container queries allow components to respond to their parent's width instead of the browser viewport.
- This makes components truly modular and reusable in any context (like a narrow sidebar).
- You must define a container context using
container-type: inline-size. - Tailwind uses the
@containerclass on parents, and@sm:,@md:modifiers on children.
Done with this concept?
Mark it complete to track your progress. No login needed.