DEV Community

Cover image for Tailwind CSS: Using dynamic breakpoints and container queries
Matt Angelosanto for LogRocket

Posted on • Originally published at blog.logrocket.com

Tailwind CSS: Using dynamic breakpoints and container queries

Written by Hamsa Harcourt✏️

Styling is a crucial component of web design, impacting how your website looks and feels to users. The right styling can improve your website’s visual appeal, usability, and professional appearance. It can also support the establishment of a website's general tone and personality.

Aside from just aesthetics, styling can have practical advantages. Users will find it simpler to consume content on your website if you use the right font sizes and styles, for example, to improve readability and legibility.

However, creating these styles from scratch is time-consuming, requiring thorough planning. Instead of starting every project from scratch, oftentimes, developers use pre-built libraries that make styling webpages simpler and more standards-compliant.

These pre-planned libraries are known as CSS frameworks, one of which is Tailwind CSS. In this tutorial, we’ll explore using dynamic breakpoints, multi-configs, and container queries with Tailwind CSS. Let’s get started!

Background: Introduction to Tailwind CSS

Tailwind CSS is a utility-first CSS framework for quickly creating custom user interfaces. Simple to use and highly customizable, Tailwind CSS provides a low-level styling solution that allows developers to easily create custom designs from scratch without having to write excess CSS.

As one of its main advantages, Tailwind CSS offers a large set of utility classes that you can use to style HTML elements. Simple to use, these classes are easy to combine in a variety of ways to achieve the desired styling for a specific element.

Despite being relatively new, Tailwind CSS has gained a lot of popularity among developers for its small size, simplicity, flexibility, and ease of use.

What are dynamic breakpoints in Tailwind CSS?

In CSS, dynamic breakpoints refer to arbitrary viewport sizes that allow a webpage to adjust its layout. Dynamic breakpoints are useful for creating responsive designs that look and function well on a variety of devices and screen sizes.

In Tailwind CSS v3.2, there are two ways to create dynamic breakpoints, the max-* variant and the min-* variant.

Using the max-* variant

The new max-* variant lets you apply max-width media queries based on your configured breakpoints:

 <h1 class="text-black max-lg:text-red-600">
  <!-- Applies`text-red-600` when screenwidth is <= 1023px  -->
 </h1>
Enter fullscreen mode Exit fullscreen mode

With the code above, our heading text will turn red whenever the screen width is within the range of 0 to 1023px.

Using the min-* variant

Unlike the max-* variant, the min-* variant lets you apply min-width media queries based on arbitrary values:

   <h1 class="text-black min-[712px]:text-red-600">
  <!-- Applies`text-red-600` when screenwidth is >=712px  -->
 </h1&gt;
Enter fullscreen mode Exit fullscreen mode

To ensure that all these dynamic breakpoints give you the expected behavior in the browser, add a screens object in your configuration file as follows:

 // tailwind.config.js
module.exports = {
  theme: {
    screens: {
      sm: "640px",
      md: "768px",
      lg: "1024px",
      xl: "1280px",
      "2xl": "1536px",
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

The Tailwind CSS v3.2.4 documentation recommends using the min-width breakpoints.

What are container queries in Tailwind CSS?

Container queries are a proposed CSS feature that allow you to apply styles to an element based on the size of its parent container rather than the viewport size. Although container queries are not a part of the official CSS specification, you can use them in your projects thanks to a variety of polyfills and libraries.

Tailwind CSS v3.2.4 released a @tailwindcss/container-queries plugin, which adds container query support to the framework using a new @ syntax to differentiate them from normal media queries.

To get started, install the plugin by running the following command:

#npm
npm install @tailwindcss/container-queries

#yarn 
yarn add @tailwindcss/container-queries
Enter fullscreen mode Exit fullscreen mode

Then, add the plugin to your tailwind.config.js file:

/** @type {import('tailwindcss').Config} */
module.exports = {
  ...
  plugins: [
    require('@tailwindcss/container-queries'),
    // ...
  ],
}
Enter fullscreen mode Exit fullscreen mode

Next, we mark an element as a container using the @container class and apply styles based on the size of that container using the container variants:

   <div class="@container">
        <div class="... block @lg:flex">
        </div>
    </div>
Enter fullscreen mode Exit fullscreen mode

In the code above, we change the display of the div to flex whenever the container is larger than 32rem. Out of the box, Tailwind CSS includes the following set of container sizes:

Name Value
xs 20rem
sm 24rem
md 28rem
lg 32rem
xl 36rem
2xl 42rem
3xl 48rem
4xl 56rem
5xl 64rem
6xl 72rem
7xl 80rem

However, you can configure which values are available by adding a containers object in your configuration file, like so:

// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      containers: {
        2xs: '16rem',
        // etc...
      },
    },
  },
}
Enter fullscreen mode Exit fullscreen mode

In addition to using one of the container sizes provided by default, you can also use any arbitrary value of your choice:

 <div class="@container">
        <div class="... block @[16rem]:flex">
        </div>
    </div&gt;
Enter fullscreen mode Exit fullscreen mode

Using multiple config files in Tailwind CSS

Tailwind CSS was designed from the ground up with customization in mind. With its config files, it's easy to make these configurations better suit our use case. We may want to have different config files for different parts of our applications; a typical example is using one config file for the customer-facing part of your application and another config for the admin part of your application.

Before Tailwind v3.2.4, developers had different workarounds to use multiple config files in Tailwind CSS. Some versions of these workarounds involved using presets and extend options. However, these workarounds don’t solve the problem because they combine multiple configs into one and generate a CSS file, thereby defeating the purpose of having multiple stylesheets.

Using the @config directive

Tailwind CSS v3.2.4 includes a new @config directive that lets you specify which Tailwind CSS config to use for that file.

Let’s assume we have a Tailwind CSS config file called tailwind.dashboard.config.js and a CSS file in which we’ll want to use the config file. We can specify what config file to use in our CSS file as follows:

@config "./tailwind.dashboard.config.js"
@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Conclusion

Dynamic breakpoints, multi-configs, and container queries are powerful Tailwind CSS features that can significantly improve the flexibility and maintainability of your design system.

With dynamic breakpoints, you can easily create responsive designs that adapt to different screen sizes and devices. Multi configs enable you to modularize and reuse configurations across projects, whereas container queries allow you to apply styles based on the dimensions of a container element rather than the viewport size.

By combining these features, you can create more robust and flexible styles that can handle a wider range of devices and screen sizes. I hope you enjoyed this article. Be sure to leave a comment if you have any questions!


Is your frontend hogging your users' CPU?

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.

LogRocket Dashboard Free Trial Banner

LogRocket is like a DVR for web apps, recording everything that happens in your web app or site. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web apps — Start monitoring for free.

Top comments (0)