How to use calc() in Tailwind CSS

Sometimes, you want to execute calculations with the built-in calc() method in CSS when working with Tailwind CSS. From version 2.1+, Tailwind CSS has provided JIT mode (Just-in-Time mode) which helps to us could do this easily.


If you're using version 2.1+ of Tailwind CSS, you enable JIT mode to can use this feature. Otherwise, if you're using version v3.x or higher, JIT mode is enabled by default. So, you may skip this step.

To enable JIT mode, you open the tailwind.config.js file and add the following code:

 module.exports = {
+ mode: "jit",
  purge: [],
  theme: {},

For more information about JIT mode, you can see more at Just-in-Time mode .


You can code immediate on the HTML class attribute

<div class="h-[calc(100vh-2rem)]">...</div>

or code with CSS syntax through the @apply rule.

.sidebar {
@apply h-[calc(100vh-2rem)];

Tailwind CSS compiler will compile the above syntax to pure CSS look like:

.h-\[calc\(100vh-2rem\)\] {
height: calc(100vh - 2rem);

Note that the syntax DOES NOT contain any whitespace.

In Tailwind version v3.x or higher, you can replace all whitespaces to _. This helps your code readability.

<div class="h-[calc(100vh_-_2rem)]">...</div>

In addition, you can use the built-in theme method of Tailwind CSS in the syntax.

<div class="h-[calc(100vh_-_theme(space.8))]">...</div>


I hope this post that helps you somewhat in working with Tailwind CSS, especially in some cases that use the calc() method to calculate. Thank you for reading. See you soon!

© lechihuy.dev made with