how do i do container queries in tailwind 4
- User
how do i do container queries in tailwind 4
- Assistant
In Tailwind CSS v4, container queries are natively supported, allowing you to apply styles based on the size of a parent container rather than the viewport. Here's how to use them:
-
Mark an Element as a Container: Add the
@containerclass to the parent element you want to act as the container.<div class="@container">
-
Apply Styles Based on Container Size: Use container query variants to apply styles to child elements when the container reaches specific sizes. Tailwind provides default container sizes ranging from
@3xs(16rem) to@7xl(80rem)[1].<div class="@container">
-
Customize Container Sizes (Optional): If the default sizes don't meet your needs, you can customize them in your
tailwind.config.jsfile.// tailwind.config.js module.exports = { theme: { extend: { containers: { '2xs': '16rem', // Adds a smaller breakpoint at 16rem 'lg': '40rem', // Overrides lg to 40rem if desired // ...other overrides... }, }, }, }; -
Use Named Containers (Optional): For complex designs with multiple nested containers, you can name containers using
@container/{name}and target specific containers with variants like@sm/{name}and@md/{name}[1].<div class="@container/main">
By leveraging container queries in Tailwind CSS v4, you can create more responsive and modular components that adapt to their parent container's size, enhancing the flexibility and maintainability of your designs.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.