How to use calc() in tailwind CSS

featured Image

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:

Related Posts

featured Image

Disable scrolling Behavior on a body with element on position fixed in mobile

Here in this article, we will learn on how to disable the scroll behavior of the body whenever we scroll over an element whose position is fixed in our mobile…

Read more
featured Image

How to Remove Underline from Links in Bootstrap.

In this article, we will learn how to remove the underline from anchor tags in Bootstrap. Just like any other HTML element, links can also be styled using CSS. We…

Read more
featured Image

How to disable the resizable property of a textarea

In this article, we will see quick ways to disable the resizable property of a textarea using CSS. In CSS, we can disable it using the resize property. Set resize…

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *