Tailwind Version 4 Container Queries — Transcript

Transcript of the free Vue.js lesson Tailwind Version 4 Container Querieswatch the video lesson.

Media queries are great for making responsive designs based on the viewport size. However, a newer CSS technology called container queries gives us even more control by building responsive designs based off the size of any parent element instead of the size of the entire viewport. The syntax for working with this Intel end is actually quite simple. First, we use the add container class to mark an element as a container.

In other words, to be the element that you're basing the container queries off of in the children. And then inside of that container element, we can use variants like at small or at mid to style these child elements based on the size of the container. Let me show you what that looks like in a quick little view project that I've booted up with npm init. Here, I've created a postcard component.

and I've given the top level element, this article, a class of container. Then down inside of that article, I've included some container queries based on the size of the article element. Here we say that I only want this div to have a flex positioning applied when it's larger than the medium size or the medium size or larger. Then the same thing down here for the width of the image, only at larger screen sizes or really larger article sizes do I want this image to be constrained to 200 pixels.

view and see what the usage looks like. It's really straightforward. It's just put directly inside of the component, which means it'll span the entire width of the page. In my app, You can see that's exactly what happens.

This card, it's a little hard to see based on the shadow here, but the card expands the full width and we do have the flex being applied because the title and the image are side by side. If I scale this down, notice that the image and the title become stacked. That's because of my media query here. but this is more than just a media query, right?

It's a container query. That means if I were to constrain the width of the containing div using W96, which would of course mean that the article itself takes up less space horizontally, then over in the browser, even at larger screen sizes, I have the image and the title stacked. Why? Because that container query is not based off of the viewport width, but rather the containing elements width.

That is the element with the at container class on it. Can't you just imagine the possibilities of what this enables? Container queries are a super powerful tool that you should start using right away. It ships out of the box with Tailwind CSS version four, but if you're still on version three, there is a handy Tailwind plugin.

to help you out.