---
title: "Resolve a CSS calc() length to pixels in C#"
url: https://recursiveai.org/onehtml/cookbook/evaluate-css-calc-length/
description: "Resolve a CSS calc() length to pixels in C#. Supply the font size, viewport size, and percentage basis yourself; no browser layout is required or performed."
version: "1.6.0"
---

# Resolve a CSS calc() length to pixels in C#

**onehtml** is a free, open-source HTML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneHtml) · [GitHub](https://github.com/recursive-ai-oss/onehtml-csharp) · [Docs](https://recursiveai.org/onehtml/docs/) · [Download example (.zip)](https://recursiveai.org/onehtml/cookbook/evaluate-css-calc-length/evaluate-css-calc-length.zip)

Supply the font size and viewport width to resolve `calc()` in pixels without laying out a page.

```shell
dotnet add package RecursiveAI.OneHtml
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneHtml.Css;

var input = "calc(2em + 5vw)";
var css = CssTree
    .ParseComponentValueList(input);
var units = QuantityKinds.Length;
if (!CssQuantity.TryParse(
        css.Values, units, out var length))
    throw new FormatException(input);
var context = LengthContext.Default
    with { FontSize = 18,
           ViewportWidth = 1000 };
var pixels = length.Resolve(context);
Console.WriteLine($"{pixels} px");
```

Unzip [the example](https://recursiveai.org/onehtml/cookbook/evaluate-css-calc-length/evaluate-css-calc-length.zip), then `dotnet run`.

Prints `86 px`: `2em` is 36 px and `5vw` is 50 px with the supplied sizes.

## The full program

The download also evaluates a percentage, a bounded length, and a root-font-relative length. It shows how to reject incompatible units before resolving the value.

```csharp
using RecursiveAI.OneHtml.Css;

var input = "calc(2em + 5vw)";
var css = CssTree
    .ParseComponentValueList(input);
var units = QuantityKinds.Length;
if (!CssQuantity.TryParse(
        css.Values, units, out var length))
    throw new FormatException(input);
var context = LengthContext.Default
    with { FontSize = 18,
           ViewportWidth = 1000 };
var pixels = length.Resolve(context);
Console.WriteLine($"{pixels} px");

PrintLength("calc(100% - 24px)", context, 640);
PrintLength("clamp(16px, 2vw, 24px)", context);
PrintLength("calc(1rem + 1em)", context with { RootFontSize = 20 });
PrintLength("calc(1px + 1s)", context);

static void PrintLength(string input, LengthContext context, double percentBasis = 0)
{
    var values = CssTree.ParseComponentValueList(input).Values;
    if (!CssQuantity.TryParse(values, QuantityKinds.LengthPercentage, out var length))
    {
        Console.WriteLine($"{input}: not a length or percentage");
        return;
    }

    var pixels = length.Resolve(context, percentBasis);
    Console.WriteLine(FormattableString.Invariant($"{input}: {pixels} px"));
}
```

`dotnet run` prints:

```text
86 px
calc(100% - 24px): 616 px
clamp(16px, 2vw, 24px): 20 px
calc(1rem + 1em): 38 px
calc(1px + 1s): not a length or percentage
```

If `TryParse` returns `false`, don’t call `Resolve` on the rejected value.

## Variations

With `PrintLength` and `context` from the full program, use an 800 px basis instead of 640 px:

```csharp
PrintLength("calc(100% - 24px)", context, 800);
```

```text
calc(100% - 24px): 776 px
```

## Related recipes

- [Get computed CSS styles in C#](https://recursiveai.org/onehtml/cookbook/computed-style-csharp/)
- [Resolve CSS variables and fallbacks in C#](https://recursiveai.org/onehtml/cookbook/resolve-css-custom-properties-with-fallback/)
- [Evaluate CSS media queries in C#](https://recursiveai.org/onehtml/cookbook/evaluate-css-media-queries/)

## The short answer

Parse the CSS value with `CssTree.ParseComponentValueList`, then use `CssQuantity.TryParse` with `QuantityKinds.Length`. Call `Resolve` with a `LengthContext` containing the values the expression needs. If the property accepts percentages, use `QuantityKinds.LengthPercentage` instead and supply the pixel value of `100%` as the second argument to `Resolve`. The input is `calc(…)`, not a whole declaration such as `width: calc(…);`.

## How do you determine a CSS length in pixels?

Start by identifying what each unit measures. `px` is already a CSS pixel, not necessarily a physical screen pixel. Absolute units have a fixed conversion in CSS; `1in` is `96px`. Relative units depend on the context:

| Unit | What supplies the value |
|---|---|
| `em` | `FontSize`, in pixels; use the relevant font size for the property you’re resolving |
| `rem` | `RootFontSize`, in pixels |
| `vw` | One percent of `ViewportWidth` in this version |
| `vh` | One percent of `ViewportHeight` in this version |

`LengthContext.Default` starts with 16 px font sizes and a zero-sized viewport. A zero viewport in the context can make a nonzero `vw` term contribute zero. Supply the actual dimensions for the scenario you’re evaluating rather than relying on those defaults. The [CSS values docs](https://recursiveai.org/onehtml/docs/css-values/#numbers-units-and-math) describe other units and font metric fallbacks.

## How do you subtract pixels from a percentage in CSS calc()?

Use `calc(100% - 24px)` with spaces around the minus sign. On the C# side, a percentage is not a pixel value on its own. For a width whose percentage is relative to a 640 px containing block, pass 640 as `percentBasis`. The result is 616 px. Pass a different basis for a different containing block; don’t substitute the viewport width unless that really is the basis. Which dimension a percentage refers to is determined by the property and its context, as described in the [CSS Values and Units specification](https://drafts.csswg.org/css-values-4/#percentages).

## Why doesn’t a CSS calc() expression resolve to pixels?

The value must be a valid calculation of an accepted type. `calc(1px + 1s)` mixes a length and a duration, so it doesn’t parse as a length. A plain number isn’t a length either. The [CSS `calc()` reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/calc) explains why the result must match the property’s type. If your expression uses `var()`, resolve the custom property in its CSS context first.

Even a successfully resolved length is not a measurement of an element. Resolving the numeric value of `width: calc(100% - 24px)` will not calculate the containing block, apply flex or grid layout, or tell you the resulting border-box width. If you need that measurement, obtain it from a rendering engine.
