Arms crossed picture of James Auble
tailwindcss logo with @container super imposed

A Tailwind Container Queries Demo

Published

I posted back in May of 2021 about media queries as they were slowly making their way into modern browsers. Since then, support for container queries has gotten much better. All recent modern browser versions now support container queries and for you TailwindCSS users, we've had a way of quickly adding container query classes to TW since October 2022.

I'm a little late to the game I see, but I figured it wasn't too late for a quick demo.

As of Jan 1, 2023, container query support must be added via the @tailwindcss/container-queries plugin. It's insanely easy to set up and use to don't think it's a pain to get going with it.

Install the Plugin 

Install the NPM package in your project.

npm install @tailwindcss/container-queries

Add it to Your Tailwind Config 

module.exports = {
  theme: {
    // ...
  },
  plugins: [
    require('@tailwindcss/container-queries'),
    // ...
  ],
}

Usage 

Let's check out a super simple example.

<div class="grid">
  <div class="m-4 grid grid-cols-2 gap-4">
    <div class="@container">
      <div class="@sm:bg-black @sm:text-white">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas consectetur voluptatem laborum dicta explicabo facere perferendis accusantium aliquam, et qui.</div>
    </div>
    <div class="@container">
      <div class="@sm:bg-orange-500 @sm:text-white">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas consectetur voluptatem laborum dicta explicabo facere perferendis accusantium aliquam, et qui.</div>
    </div>
    <div class="@container">
      <div class="@sm:bg-purple-500 @sm:text-white">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas consectetur voluptatem laborum dicta explicabo facere perferendis accusantium aliquam, et qui.</div>
    </div>
  </div>
</div>

All I've done is created a CSS Grid with three children. By adding @container to the top level element of each child, I'm declaring THAT element to be a watched container. Hence forth, any children using the syntax @sm, @md, @lg, etc... will be watching for the width (in our case) of its parent div.@container.

You can find all the default container sizes here.

Code on web assassins!

Scrolldown Icon