Responsive component styling with Tailwind CSS container queries (@container)
Quick Answer
Add @container to a parent, then use `@[size]:` prefixes (e.g., `@md:text-lg`) on children to apply styles when the container exceeds that width — no media queries needed.
1<div class="@container">
2 <div class="bg-white rounded-lg shadow p-4 @md:p-8 @lg:flex @lg:gap-6">
3 <img src="/image.jpg" alt="Product" class="w-full @lg:w-48 @lg:flex-shrink-0 rounded-lg object-cover" />
4 <div class="mt-4 @lg:mt-0">
5 <h2 class="text-lg @md:text-xl @lg:text-2xl font-bold">Product Name</h2>
6 <p class="text-sm @md:text-base text-gray-600 mt-2">Product description goes here. The layout changes based on the container width, not the viewport.</p>
7 <button class="mt-4 @md:mt-6 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">Add to cart</button>
8 </div>
9 </div>
10</div>Container queries are one of CSS's most exciting modern features. They let you style a component based on its container width, not the viewport. This is a game changer for component libraries and design systems because it means a card component can adapt its layout regardless of where it's placed. Tailwind supports container queries natively with @container and @sm:/@md:/@lg: prefixes.
@media queries respond to viewport size; @container queries respond to a component's parent container size. Use media queries for page layout, container queries for reusable components.
Container queries landed in all major browsers in 2023 (Firefox, Chrome, Safari, Edge). They're stable and safe to use in production.
This free html code snippet for container queries example is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this advanced-level example will help you implement container queries example quickly and correctly.
All snippets in the Snippetly library follow html best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses html.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.