---
title: "Render a CSS grid to PNG in C#"
url: https://recursiveai.org/onerender/cookbook/render-css-grid-to-image/
description: "Render a CSS grid to PNG in C#, inspect cell positions and sizes, and compare fixed and flexible columns with a runnable .NET example."
version: "1.4.0"
---

# Render a CSS grid to PNG in C#

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

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneRender.Image) · [GitHub](https://github.com/recursive-ai-oss/onerender-csharp) · [Docs](https://recursiveai.org/onerender/docs/) · [Download example (.zip)](https://recursiveai.org/onerender/cookbook/render-css-grid-to-image/render-css-grid-to-image.zip)

Render grid rows and columns to an image, then read their cell coordinates. The HTML input is in the zip and shown below.

```shell
dotnet add package RecursiveAI.OneRender.Image
```

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

Save this as `input.html`:

```html
<style>
body { margin:0 }
main { display:grid; grid-template-columns:100px 1fr;
       grid-auto-rows:40px; gap:10px }
div { background:#2563eb; color:white }
</style><main><div id="a">A</div><div id="b">B</div>
<div id="c">C</div><div id="d">D</div></main>
```

```csharp
using OneRender.Image;

var image = HtmlRender.ToImage(
    File.ReadAllText("input.html"),
    new HtmlRenderOptions { Width = 320, Height = 120 });
File.WriteAllBytes("grid.png", image.ToPng());
Console.WriteLine("grid.png: 320x120");
```

```text
grid.png: 320x120
```

Unzip [the example](https://recursiveai.org/onerender/cookbook/render-css-grid-to-image/render-css-grid-to-image.zip), then `dotnet run`.

## The full program

```csharp
using OneRender;
using OneRender.Image;
using OneRender.Interaction;
using OneRender.Painting;

string html = File.ReadAllText("input.html");
const int width = 320;
var ui = InteractivePage.Create(html,
    new HtmlPageOptions(FontProviders.CreateDefault())
    { ViewportWidth = width, ViewportHeight = 120 });
foreach (string id in new[] { "a", "b", "c" })
{
    var rect = ui.Layout.GetBoundingClientRect(
        ui.Page.Document.GetElementById(id));
    Console.WriteLine($"{width} #{id}: {rect.X},{rect.Y} {rect.Width}x{rect.Height}");
}
var list = new DisplayList();
ui.Page.Paint(list);
var image = DisplayListRasterizer.Render(list, width, 120);
File.WriteAllBytes($"grid-{width}.png", image.ToPng());
Console.WriteLine($"grid-{width}.png: {image.Width}x{image.Height}");
```

`dotnet run` prints:

```text
320 #a: 0,0 100x40
320 #b: 110,0 210x40
320 #c: 0,50 100x40
grid-320.png: 320x120
```

![Grid at 320 pixels wide: two columns and two rows](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAAB4CAMAAAC0ENvsAAABwlBMVEUlY+v///88c+2gu/Zjj/FaifCNrfWIqvR2nfJDeO6LrPTw9P7S3/tei/BWhvBij/GVs/X7/P+SsfXJ2fp8ofNKfe5Qge9plPGvxvj4+v4pZutOgO+nwPcwa+z2+f6buPakvvf5+/4qZuucuPazyPjq8P0oZetEeu7r8P2Pr/UnZevP3PsmZOtjkPFkkPHT3/u+0fnR3vu2yvhCeO5fjPDG1vpymvJ1nPL6+/+1yvgvauyMrPRok/GtxPeFqPS6zvkzbezZ5PwtaexXh/B+o/PU4PtwmPLl7f3Q3ftbifD8/f+GqPR/o/Pb5fy4zPhhjvHg6fyjvfdQgu+yyPi5zfm3y/jH1/rY4/uApPMmY+srZ+wuaexAdu2BpfObt/ahvPaUsvV3nfJEee6HqfRMf++eufZul/I7c+02b+1Vhu+owfdYh/BvmPLX4vtPge+MrfT6+/4/de2mv/fu8/0+de3v9P6at/ZThO+Ep/Tp8P1tl/LL2vrm7f3V4fvc5vzv8/67zvna5PyJqvRmkvFumPJJfe7y9v6RsPUybezB0/ni6vxBd+60yvjI2Pqdufaxx/jW4fu+0Pm8z/nK2fp7oPMqZ+tQRcEPAAADAElEQVR4nO3cv2sTARjG8ec9r5e7aEdjaS2K0BRqEBUHQQVREApdnBStQyddrC7+KOpSHISKguAgiJt0K/QPcKyDi4KjVkQd+gNEa7Rg1TgUa8VFeHzf0PB8pgyFp/1yTY5LLoYAtvKoETEXKmn2L7DWKSDJACAx++Y+AgBIDYCZLXrOhTIAKJvV3UeWnwPb60VqZvbecy9SAgBF8Xlj0F6B9oWPH0qlzqA9dymALrNu+6ef/l9yi91zlADIZ99mWTVwtDfPXwXOuUqAvrwXxcs8arFj5665cjlqzd06YEuWdWWbs3d+I6v+X9d/aUzP7G6bq73xmwuVAEUBNEqvD8aNPp7a+ixuzVeKQ0/qAA7PbA+d7XkaOecoQZoBwOyRNHC1v611TmMGbL9NAt+LyaM24T7XX57oPGBmrXMaE/KH/HE1prrHfoxHrMaID9hidDWGpIAkBSQpIEkBSQpIUkCSApIUkKSAJAUkKSBJAUkKSFJAkgKSFJCkgCQFJCkgSQFJCkhSQJICklrnMxZNoiOQpIAkBSQpIEkBSQpIUkCSApIUkKSP+JJ0BJIUkGQABs3MzB64juD3HeunHg7ed9uKlqJv33wl7M6XpfZ6MWT5+Fm7E7Lnz3DO7DaA6sAtx5FfGpX5yixwZnqH3XSbi9V5oWP5Qbffhq1AxTYBwLBd9JuLdckuu2/8HRAjG9xXYyRTzXkhTs43Y9VB+hyPmrGbtMpbCelXLDRhttYyAZPFvuM1AMBo5Oyx0cj7uz0lONF2sgbgRilwdbi092rgnKcUV8ZsyK5fW3oRMddfnhgxu9djnyLWwlRPj7l+Z8eq0xjUqne3eW5F0+Uskq7GkBSQpIAkBSQpIEkBSQpIUkCSApIUkKSAJAUkKSBJAUkKSFJAkgKSFJCkgCQFJCkgSQFJCkhSQJLuWCfpCCQpIEkBSQpIUkCSApIUkKSAJAUkKSBJAUkKSFJAkgKSFJCkgCQFJCkgSQFJCkhSQJICkhSQpIAkBSQpIEkBSQpIUkDSTybBVufZbpa5AAAAAElFTkSuQmCC)

## Variations

### Use equal columns

Replace the HTML-loading line in the full program:

```csharp
string html = File.ReadAllText("input.html")
    .Replace("100px 1fr", "1fr 1fr");
```

The full program then prints:

```text
320 #a: 0,0 155x40
320 #b: 165,0 155x40
320 #c: 0,50 155x40
grid-320.png: 320x120
```

## Related recipes

- [Load local CSS and images for HTML to PDF in C#](https://recursiveai.org/onerender/cookbook/load-html-render-resources/)
- [Render responsive flexbox to PNG in C#](https://recursiveai.org/onerender/cookbook/render-css-flexbox-to-image/)
- [Scroll a rendered HTML container in C#](https://recursiveai.org/onerender/cookbook/scroll-rendered-html-page/)

## The short answer

Pass HTML containing `display:grid` to `HtmlRender.ToImage`, choose the viewport, and save the returned image with `ToPng()`. Use `InteractivePage` when you also need cell geometry: its layout queries return each element’s bounding rectangle, and its underlying page paints the same layout to a display list for rasterization.

The example uses one fixed column and one flexible column, with automatic rows. It needs no JavaScript, network resources or input images. The blue cells are CSS backgrounds. The packaged default fonts render their labels.

## How do I render a CSS grid to PNG in C#?

Use the snippet at the top for file output only. Use the full program to inspect layout before saving. The latter creates a page at 320 by 120 CSS pixels, reads the rectangles for A, B and C, paints a display list and rasterizes it at the same dimensions. Matching those dimensions avoids confusing the layout viewport with the output canvas.

This is a render of supplied HTML, not a capture of a running website. Generate the markup before the call. If a grid depends on JavaScript to insert items or change classes, supply the resulting markup yourself. For external images or stylesheets, provide resource bytes explicitly with the [resource-loading recipe](https://recursiveai.org/onerender/cookbook/load-html-render-resources/).

## How does grid-template-columns work?

In this example, `100px 1fr` fixes the first column at 100 pixels and gives the remaining space to the second column after the gap. At a container width of 320 pixels with a 10-pixel gap, that leaves 210 pixels. The printed rectangles show A at x=0 with width 100, and B at x=110 with width 210. C returns to x=0 on the next row.

The equal-column variation replaces that definition with `1fr 1fr`. The same available space is divided into two 155-pixel columns, with the second starting at x=165. That result comes from changing the CSS and laying it out again, not resizing a finished bitmap.

OneRender documents line placement, spans, negative lines, named areas and automatic placement in its [grid architecture](https://github.com/recursive-ai-oss/onerender-csharp/blob/d9708ace1863cae70a1b0782b8363ed970e555bb/docs/architecture.md#grid-layout-layoutgrid).

## How do I add a gap to a CSS grid?

Set `gap` on the grid container. Here it separates both columns and rows. A cell is 40 pixels tall and the next row begins at y=50: the extra 10 pixels are the row gap. It is not padding around the outer boundary. Keep body margin explicit when you want coordinates to start at the image’s top-left corner.

The renderer’s supported grid behavior is not every possible CSS layout. At this pin, the documentation says inline-axis baseline falls back to start, last-baseline container baselines are not produced, and `justify-items:legacy` computes to `normal`. It also lists masonry, fragmentation across pages and non-horizontal writing modes as unimplemented. For the PNG task here, use horizontal rows and ordinary tracks; do not infer paged grid support from a successful image render.

[MDN’s grid guide](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Grid_layout) explains the CSS concepts independently of the renderer.
