Ever built a component that looks perfect in your main content but breaks in the sidebar? ?
Media queries only solve half the problem - they care about screen size, not where your component actually lives. That's where Container Queries come in.
Let's say you've built this card component:
@media (min-width: 768px) { .card { display: flex; gap: 2rem; } }
Looks great on mobile and desktop! Until... your teammate puts it in a narrow sidebar. Now your "desktop" layout is trying to squeeze into a 300px space. Ouch.
Looking to boost your CSS skills? Check out "Modern CSS Techniques That Replaced My JavaScript" to see how pure CSS can replace complex JavaScript code.
Instead of asking "how wide is the screen?", Container Queries ask "how wide is my container?" Here's how they work:
/* Step 1: Mark the container */ .card-wrapper { container-type: inline-size; } /* Step 2: Style based on container width */ @container (min-width: 400px) { .card { display: flex; gap: 2rem; } }
Now your card adapts to its container, not the screen. Put it anywhere - it just works!
Here's a product card that adapts to any space:
<div> <pre class="brush:php;toolbar:false">.product-wrapper { container-type: inline-size; } /* Mobile-first: Stack everything */ .product { display: grid; gap: 1rem; padding: 1rem; background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } /* Medium container: Side-by-side layout */ @container (min-width: 400px) { .product { grid-template-columns: 200px 1fr; } } /* Large container: More sophisticated layout */ @container (min-width: 600px) { .product .content { display: grid; grid-template-columns: 1fr auto; align-items: start; } .product .desc { grid-column: 1 / -1; } }
Good news! Container Queries work in all modern browsers. For older browsers, your mobile layout becomes the fallback:
/* Default mobile layout */ .product { display: grid; } /* Enhance for modern browsers */ @supports (container-type: inline-size) { /* Container query styles */ }
Want to nail those UI details? "12 Frontend Micro-Interactions That Users Secretly Judge" reveals the subtle interactions that make websites feel polished.
Drop a comment if you build something cool with Container Queries! ?
The above is the detailed content of Stop Fighting with Media Queries! Use CSS Container Queries Instead. For more information, please follow other related articles on the PHP Chinese website!