Sub topic 1
Why Container Queries in Tailwind CSS: Viewport Versus Container
Prerequisites
You should know basic HTML and CSS layout, including flexbox and grid. You should also know Tailwind utility classes and viewport variants such as md: and lg:.
Viewport Queries Versus Container Queries
A viewport query changes styles according to the browser window. For example, md:flex-row applies when the viewport reaches Tailwind's md breakpoint. This works well for page-level layouts.
A container query changes styles according to an element's available width. This makes a component reusable in different locations. The same card can stack its content in a narrow sidebar and use a horizontal layout in a wide main column, even when the viewport stays the same.
Marking a Container with `@container`
Add @container to the ancestor whose width should control its descendants. Then use container variants on child elements.
<div class="@container">
<div class="flex flex-col gap-4 @md:flex-row">
<img class="w-full @md:w-48" src="/photo.jpg" alt="Product photo" />
<div>
<h2 class="text-lg font-semibold">Product name</h2>
<p class="text-sm text-gray-600">Short description of the product.</p>
</div>
</div>
</div>The outer div becomes a query container. The child starts as a column and changes to a row when its container reaches the @md size. The child responds to the marked ancestor, not directly to the viewport.
Styling Children with `@sm`, `@md`, and `@lg`
Container variants use the same general size names as responsive variants, but the @ prefix identifies them as container-based:
@sm:grid-cols-2applies when the container reaches the small size.@md:flex-rowapplies at the medium container size.@lg:gap-8applies at the large container size.
Use the unprefixed utility as the narrow default, then add variants for wider containers.
Exercise
Which width controls @md:flex-row when the element has an ancestor with @container?
Show answer
The width of the nearest query container, not the browser viewport.