- Published on
How to Use calc() in Tailwind CSS
- Authors
- Name
- Ripal & Zalak
calc()
in Tailwind CSS
How to Use The calc()
function in CSS allows you to perform calculations directly in styles. In Tailwind CSS, you can use calc()
within arbitrary values to create dynamic layouts.
calc()
in Tailwind
Basic Usage of Tailwind allows the use of calc()
inside brackets []
for dynamic styling:
<div class="h-[calc(100vh-4rem)] w-[calc(100%-2rem)] bg-blue-500">Responsive Width and Height</div>
calc()
Expressions
Handling Spaces in Since Tailwind class names do not support spaces within square brackets, use underscores _
or remove spaces:
<div class="h-[calc(100vh_-_4rem)] w-[calc(100%_-_2rem)] bg-green-500">
Using underscores to replace spaces
</div>
calc()
with Tailwind Theme Variables
Using You can use calc()
with Tailwind’s theme variables, such as spacing:
<div class="h-[calc(100vh-theme(space.7))] bg-gray-300">Using theme variables</div>
Alternatively, reference Tailwind’s theme values in your CSS:
.content-container {
height: calc(100vh - theme('spacing.7'));
}
calc()
Values
Custom Tailwind Config for To reuse calc()
values, extend your tailwind.config.js
:
module.exports = {
theme: {
extend: {
height: {
'screen-minus-nav': 'calc(100vh - 3rem)',
},
},
},
}
Then, use it in your HTML:
<div class="h-screen-minus-nav bg-red-500">Custom height using Tailwind configuration</div>
FAQs
calc()
in Tailwind for margin, padding, or width?
1. Can I use Yes! You can use calc()
for any numeric CSS property:
<div class="w-[calc(50%-10px)] p-[calc(1rem+5px)]">Custom padding and width</div>
calc()
does not work in Tailwind?
2. What if Ensure that:
- You are using Tailwind v3.0 or later.
- There are no spaces in your class definition (use underscores
_
). - Your Tailwind build process includes arbitrary values.
theme()
function in JavaScript?
3. Can I use Tailwind’s Yes, you can use theme()
to retrieve values dynamically:
const heightValue = `calc(100vh - ${theme('spacing.7')})`