Open In App

How to use calc() in Tailwind CSS?

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The calc() function in CSS allows you to perform calculations for property values dynamically. While Tailwind CSS doesn’t directly support calc(), you can use it inline or with custom utilities.

1. Using Inline Styles

You can use calc() directly within the style attribute for dynamic property values.

HTML
<html>
<head>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="h-screen flex items-center justify-center
             bg-gray-200">
    <div style="width: calc(100% - 50px);" class="bg-blue-500
         text-white p-5">
        Width is 100% minus 50px
    </div>
</body>
</html>

In this Example:

  • Inline style is used to apply the calc() function to set a dynamic width.
  • Tailwind classes like bg-blue-500 and p-5 are combined with the inline style.

2. Using Arbitrary Values

Tailwind CSS supports arbitrary values using square brackets, allowing you to integrate calc() directly into your classes.

HTML
<html>
<head>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="h-screen flex items-center justify-center
             bg-gray-200">
    <div class="w-[calc(100%-50px)] bg-green-500
                text-white p-5">
        Width is 100% minus 50px
    </div>
</body>
</html>
  • The w-[calc(100%-50px)] utility sets the width using the calc() function within Tailwind's arbitrary value syntax.
  • This method avoids inline styles, keeping the code clean and consistent with Tailwind's utility-first approach.

Next Article

Similar Reads