乐闻世界logo
搜索文章和话题

How to use calc in tailwindcss?

3个答案

1
2
3

In Tailwind CSS, you can utilize the CSS calc() function in several ways to create dynamic property values. This includes inline styles, custom CSS classes, and leveraging Tailwind's Arbitrary Values feature. Below is a detailed guide on implementing calc() within Tailwind CSS:

Combining with Tailwind CSS Configuration

Add custom widths to your Tailwind CSS configuration file:

javascript
// tailwind.config.js module.exports = { // ... theme: { extend: { width: { 'calc-example': 'calc(100% - 2rem)', }, }, }, // ... };

Then apply this new configuration class in your HTML:

html
<div class="w-calc-example ..."> <!-- Content --> </div>

Using Tailwind's Arbitrary Values

Tailwind allows inline arbitrary values—including calc()—by using square brackets [] in class names:

html
<div class="w-[calc(100%_-_2rem)] ..."> <!-- Content --> </div>

Note: Spaces within calc() must be represented using underscores _ because values containing spaces or special characters require proper escaping when using Arbitrary Values in Tailwind CSS.

These are the primary methods for using calc() in Tailwind CSS. Always ensure spaces are included before and after operators (e.g., +, -, *, /) to prevent parsing errors.

2024年6月29日 12:07 回复

theme()

Use the theme() function to access Tailwind configuration values via dot notation.

When you need to reference only a portion of the theme configuration within a declaration, this can serve as a useful alternative to @apply.

shell
.content-container { height: calc(100vh - theme('spacing.7')); }
2024年6月29日 12:07 回复

Avoid adding spaces within calc() expressions.

shell
class="w-[calc(100%+2rem)]"

Alternatively, use underscores to replace spaces.

shell
<script src="https://cdn.tailwindcss.com"></script> <div class="h-20 w-[calc(100%_-_10rem)] bg-yellow-200"></div>

We can also utilize theme variables.

shell
h-[calc(100%-theme(space.24))]
2024年6月29日 12:07 回复

你的答案