Container queries in Tailwind

Container queries are here in @tailwindcss.

Container queries are changing the game. They make your UI components more robust and resilient.

Browser support is getting really good, so it's time to embrace a new CSS/Tailwind skill!

Transcript

00:00 Container queries. Browser support is getting pretty good and you can now use them in Tailwind CSS. Let's take a look. Here's a responsive card where the layout changes at the small break point. You can see the image goes to the left instead of from the top. Here's a code for the card and you can see it's using the small break point to make changes. So that all works well but now let me

00:18 create a grid with two columns. Inside of that grid I will paste the exact same card two times so they show up side by side. Obviously when we have two columns we have much less horizontal space but the card still relies on the viewport width to make the layout changes. Utilities for container queries will eventually make it to Tailwind CSS core but for the time being you can

00:36 bring it through a first-party plugin. npm install dash d at Tailwind CSS slash container queries and now in the Tailwind config file I can require that plugin. All right let's start working with the card in the first column. I wrap this card in a div with a class of

00:53 at container and this will define the container type inline size to this block of html. Now I want to change all the sm utilities to instead use container queries. So I can use at and this will give me a list of at container break points. Those are based on the default max width scale not the default media query break point and of course you can customize all of that.

01:12 I'll go with 36 rem so at xl and now we've replaced our media query break point with break points listening to the container width. The container has more than 36 rem in width so we've switched to the side-by-side layout but as I keep growing you can see that now the container

01:28 is back to below 36 rem so instead of breaking like this card that listens to the whole viewport width this is aware of its own container so let's keep going until we hit that container width again and it should switch back to a side-by-side layout. Beautiful and just to appreciate how it works we

01:46 have three columns and then two columns and right away you can see the container queries have deemed that there's not enough space to switch to the horizontal layout. Let's make the window narrow and you can see now our two columns have shifted to this vertical layout and eventually if they have enough space horizontally again you can see that all cards switch to this horizontal layout

02:06 but will eventually go back to the vertical layout. So that's container queries in Tailwind CSS be sure to check out the browser support before you use them and also check out the plugins github repo for full documentation.

More Tips