2

I'm trying to use custom spacing variables from my Tailwind theme inside a calc() expression, but it doesn’t seem to work.

In my input.css, I added custom spacing like this:

@theme {
  --spacing-my-custom-height: 10rem;
  --spacing-my-custom-height-2: 5rem;
}

Then in my HTML, I tried using them like this:

<div class="size-my-custom-height bg-green-800">
  <!-- Works -->
  <div class="size-my-custom-height-2 bg-green-600"></div>
</div>

<div class="size-my-custom-height bg-green-800">
  <!-- Doesn't work -->
  <div class="size-[calc(100%-(my-custom-height-2))] bg-green-600"></div>
</div>

How can I correctly use Tailwind's custom spacing variables inside a calc() expression in utility classes?

  • TailwindCSS v4.1
  • Installation mode: CLI

Note: There is no error in the terminal.

2
  • 1
    Related for CSS variable using: developer.mozilla.org/en-US/docs/Web/CSS/var Commented Sep 5 at 7:12
  • 1
    For using CSS variables, Tailwind CSS provides a shortened syntax, but even there the -- prefix is not omitted. It's only meant to make writing shorter class names easier. If you just want to reference a variable without calc(), you can use size-(--my-custom-height) instead of size-[var(--my-custom-height)] (but both are correct). See more: tailwindcss.com/docs/… Commented Sep 5 at 7:15

1 Answer 1

2

When using arbitrary value classes, the value inside the square brackets [] should be a valid CSS value as-is. Though, there is special treatment for mathematic functions like calc(), min(), etc. where spaces can be removed.

Thus, if we look at the value you wrote, calc(100% - (my-custom-height-2)), this is an invalid CSS value. It seems like you're trying to reference your --spacing-my-custom-height-2 theme token. This would be exposed as a CSS variable so we can use CSS's var() function to reference it: calc(100% - var(--spacing-my-custom-height-2)). Thus, using it in an arbitrary value class:

<script src="https://unpkg.com/@tailwindcss/[email protected]"></script>

<style type="text/tailwindcss">
@theme {
  --spacing-my-custom-height: 10rem;
  --spacing-my-custom-height-2: 5rem;
}
</style>

<div class="size-my-custom-height bg-green-800">
  <!-- Works -->
  <div class="size-my-custom-height-2 bg-green-600"></div>
</div>


<div class="size-my-custom-height bg-green-800">
  <!-- Doesn't work -->
  <div class="size-[calc(100%-var(--spacing-my-custom-height-2))] bg-green-600"></div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.