Container Queries
Container queries have a simple concept - they're just like normal @media
queries, but based on an element's container size rather than the viewport size.
The huge benefit of container queries is it means a component can be styled based on its own width, so it can be dropped into a sidebar, content section or anywhere else and it will just work.
@container (min-width: 512px) {
.card {
padding: 20px;
}
}
<div class="@container">
<div class="card @lg:p-5">
</div>
</div>
The below shows the exact same card component in an assortment of different grids, which is a common requirement. It doesn't even matter if we bring in a sidebar at a certain screen size - container queries ensure the card will always will use the appropriate styling!
My Card Title
A short blurb lorem ipsum dolor sit amet, consectetur adipiscing elitsc. Maecenas a quam semper, vestibulum arcu id, venenatis erat.
My Card Title
A short blurb lorem ipsum dolor sit amet, consectetur adipiscing elitsc. Maecenas a quam semper, vestibulum arcu id, venenatis erat.
My Card Title
A short blurb lorem ipsum dolor sit amet, consectetur adipiscing elitsc. Maecenas a quam semper, vestibulum arcu id, venenatis erat.
My Card Title
A short blurb lorem ipsum dolor sit amet, consectetur adipiscing elitsc. Maecenas a quam semper, vestibulum arcu id, venenatis erat.
My Card Title
A short blurb lorem ipsum dolor sit amet, consectetur adipiscing elitsc. Maecenas a quam semper, vestibulum arcu id, venenatis erat.
My Card Title
A short blurb lorem ipsum dolor sit amet, consectetur adipiscing elitsc. Maecenas a quam semper, vestibulum arcu id, venenatis erat.
My Card Title
A short blurb lorem ipsum dolor sit amet, consectetur adipiscing elitsc. Maecenas a quam semper, vestibulum arcu id, venenatis erat.
My Card Title
A short blurb lorem ipsum dolor sit amet, consectetur adipiscing elitsc. Maecenas a quam semper, vestibulum arcu id, venenatis erat.
My Card Title
A short blurb lorem ipsum dolor sit amet, consectetur adipiscing elitsc. Maecenas a quam semper, vestibulum arcu id, venenatis erat.
<div className="@container">
<div className="card rounded-2xl bg-indigo-100">
<img className="rounded-2xl" src="..." alt="..." />
<div className="p-3 @xs:p-5 @lg:p-7">
<p className="@xs:text-lg @lg:text-2xl">My Card Title</p>
<p className="hidden @lg:block">A short blurb...</p>
</div>
</div>
</div>
I do quite like the Tailwind implementation of container queries. You simply use @container
to define your context, and then @xs:
, @sm:
etc. instead of the usual viewport prefixes. Bear in mind though that the sizes are different - the default sizes can be found in the plugin repo readme.
@container (min-width: 320px) {
.card .text {
padding: 1.25rem;
}
.card .title {
font-size: 1.125rem;
}
}
@container (min-width: 512px) {
.card .text {
padding: 1.75rem;
}
.card .title {
font-size: 1.5rem;
}
.card .blurb {
display: block;
}
}
Container Queries
Menu