Sub topic 2
CSS Variables and `calc()` in Tailwind CSS
Assume you know basic CSS custom properties, units, selectors, and Tailwind utilities such as p-4, hover:bg-blue-500, and md:. Tailwind's theme handles common values. Square brackets let you use a value or property that is specific to one component.
CSS variables and `calc()`
Put a CSS value inside brackets after a utility. Tailwind copies the value into the generated CSS. Use underscores where CSS requires spaces.
<section
class="[--header-height:72px] lg:[--header-height:64px]
min-h-[calc(100vh-var(--header-height))]
scroll-mt-[var(--header-height)]"
>
Page content
</section>Here, [--header-height:72px] defines a custom property on the section. The lg: variant changes it on large screens. var(--header-height) reads the property, while calc() subtracts it from the viewport height.
Arbitrary properties for CSS with no utility
An arbitrary property uses the form [property:value]. This writes a CSS declaration directly. It is useful when Tailwind has no matching utility.
<div class="[mask-type:luminance] hover:[mask-type:alpha]">
Masked content
</div>The first class sets mask-type: luminance. The hover: prefix applies the second declaration only while the pointer is over the element. You can also define custom properties this way, as shown in the previous section.
Use an arbitrary property for a local exception. If the same property and value appear across many components, add a named theme value or a component style instead.
Using variants with arbitrary values
Arbitrary values work with state, responsive, and other variants. The variant comes before the complete bracket expression.
<div
class="w-[317px] bg-[#bada55]
hover:w-[360px]
md:grid md:grid-cols-[1fr_500px_2fr]
dark:bg-[color:var(--panel-dark)]"
>
Content
</div>This element changes width on hover, becomes a grid at the md breakpoint, and reads a dark-mode color from a CSS variable. Keep every possible class name complete in the source. Tailwind scans text statically, so constructing w-[${width}px] dynamically will not generate the needed CSS.
Exercise
How would you make an element use a 56px scroll offset by default and 44px at the lg breakpoint?
Show answer
Use class="[--scroll-offset:56px] lg:[--scroll-offset:44px] scroll-mt-[var(--scroll-offset)]".