Open In App

How to use calc() in Tailwind CSS?

Last Updated : 11 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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>
<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>
<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.

How to use calc() in Tailwind CSS – FAQs

Can I use calc() with responsive utilities in Tailwind CSS?

Yes, use arbitrary values within responsive classes like md:w-[calc(100%-50px)].

What are the advantages of using calc() in Tailwind CSS?

calc() allows for dynamic calculations, making it ideal for layouts requiring flexible spacing or dimensions.

Is calc() supported by all browsers?

Yes, calc() is widely supported in modern browsers.

Can I combine calc() with Tailwind’s percentage utilities?

Yes, you can combine calc() with percentage-based utilities using arbitrary values, e.g., h-[calc(50%-20px)].

Do I need to enable any specific configuration in Tailwind CSS to use calc()?

No additional configuration is needed for inline styles or arbitrary values, but custom utilities require updates to tailwind.config.js.




Similar Reads

three90RightbarBannerImg