How to use calc() in tailwind CSS

Tailwind CSS provides utility classes for rapid UI development. The calc() CSS function allows complex calculations to determine element sizes responsively.

Here’s how to leverage calc() with Tailwind CSS for dynamic designs.

What is calc()?

The calc() CSS function allows mathematical expressions to set property values like width, margin, font-size etc.

For example:

.box {
  width: calc(100%-20px);
} 

This sets the width to 100% minus 20px.

You can mix units and use math operators inside calc().

Benefits of Using calc()

Here are some benefits of using calc():

  • Dynamic sizes relative to parent elements
  • Mix percentages and fixed units like px, rem etc
  • Simpler responsive design without media queries
  • More flexibility than hardcoded pixel values

How to Use calc() in Tailwind CSS

Let’s look at some examples of using calc() with Tailwind utilities:

1. Width Utilities

Set a width relative to its parent:

<!-- Full width minus padding -->
<div class="w-[calc(100%-2rem)] px-10">
</div>

Here, calc(100% - 2rem) calculates the width as 100% of the parent minus 2rem. So it sets the div width to take up the full parent width minus 2rem on left and right.

IMPORTANT : Do not use white space in calc(). You can use _ (underscore) or no whitespace at all.

2. Spacing Utilities

Add customized spacing:

<!-- 1rem + 5px margin -->
<div class="mt-[calc(1rem+5px)]">
</div>

3. Font Size Utilities

Calculate responsive font sizes:

<!-- Bigger font on small screens -->  
<h1 class="text-lg sm:text-[calc(1.5rem+2vw)]">
</h1>

4. Custom Utilities

Extend existing utilities:

<!-- Custom margin -->
<div class="mt-[calc(1rem-2px)]">
</div>

Conclusion

The calc() function brings dynamic sizing and new possibilities for responsive design in Tailwind CSS. Give it a try next time you need calculated CSS values!


Related Articles:

Install Tailwind CSS in Vue 3 and Vite App

Scroll to Top