Published on

How to Use calc() in Tailwind CSS

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Use calc() in Tailwind CSS

The calc() function in CSS allows you to perform calculations directly in styles. In Tailwind CSS, you can use calc() within arbitrary values to create dynamic layouts.

Basic Usage of calc() in Tailwind

Tailwind allows the use of calc() inside brackets [] for dynamic styling:

<div class="h-[calc(100vh-4rem)] w-[calc(100%-2rem)] bg-blue-500">Responsive Width and Height</div>

Handling Spaces in calc() Expressions

Since Tailwind class names do not support spaces within square brackets, use underscores _ or remove spaces:

<div class="h-[calc(100vh_-_4rem)] w-[calc(100%_-_2rem)] bg-green-500">
  Using underscores to replace spaces
</div>

Using calc() with Tailwind Theme Variables

You can use calc() with Tailwind’s theme variables, such as spacing:

<div class="h-[calc(100vh-theme(space.7))] bg-gray-300">Using theme variables</div>

Alternatively, reference Tailwind’s theme values in your CSS:

.content-container {
  height: calc(100vh - theme('spacing.7'));
}

Custom Tailwind Config for calc() Values

To reuse calc() values, extend your tailwind.config.js:

module.exports = {
  theme: {
    extend: {
      height: {
        'screen-minus-nav': 'calc(100vh - 3rem)',
      },
    },
  },
}

Then, use it in your HTML:

<div class="h-screen-minus-nav bg-red-500">Custom height using Tailwind configuration</div>

FAQs

1. Can I use calc() in Tailwind for margin, padding, or width?

Yes! You can use calc() for any numeric CSS property:

<div class="w-[calc(50%-10px)] p-[calc(1rem+5px)]">Custom padding and width</div>

2. What if calc() does not work in Tailwind?

Ensure that:

  • You are using Tailwind v3.0 or later.
  • There are no spaces in your class definition (use underscores _).
  • Your Tailwind build process includes arbitrary values.

3. Can I use Tailwind’s theme() function in JavaScript?

Yes, you can use theme() to retrieve values dynamically:

const heightValue = `calc(100vh - ${theme('spacing.7')})`