---
title: "Render responsive flexbox to PNG in C#"
url: https://recursiveai.org/onerender/cookbook/render-css-flexbox-to-image/
description: "Render a wrapping CSS flexbox layout at two viewport widths in C# and inspect the changed item positions before writing PNG images."
version: "1.4.0"
---

# Render responsive flexbox 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-flexbox-to-image/render-css-flexbox-to-image.zip)

Render the same flex layout at two widths to see where items wrap. 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:flex; flex-wrap:wrap; gap:10px }
div { flex:0 0 100px; height:40px;
      background:#2563eb; color:white }
</style><main><div id="a">A</div><div id="b">B</div>
<div id="c">C</div></main>
```

```csharp
using OneRender.Image;

foreach (int width in new[] { 320, 210 }) {
    var image = HtmlRender.ToImage(
        File.ReadAllText("input.html"),
        new HtmlRenderOptions { Width = width, Height = 120 });
    File.WriteAllBytes($"flex-{width}.png", image.ToPng());
    Console.WriteLine($"flex-{width}.png: {image.Width}x{image.Height}");
}
```

```text
flex-320.png: 320x120
flex-210.png: 210x120
```

Unzip [the example](https://recursiveai.org/onerender/cookbook/render-css-flexbox-to-image/render-css-flexbox-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");
foreach (int width in new[] { 320, 210 })
{
    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($"flex-{width}.png", image.ToPng());
    Console.WriteLine($"flex-{width}.png: {image.Width}x{image.Height}");
}
```

`dotnet run` prints:

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

![Flexbox at 320 pixels wide: three items in one row](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAAB4CAMAAAC0ENvsAAABelBMVEUlY+v///88c+2gu/Zjj/FaifCNrfWIqvR2nfJDeO5Adu2BpfObt/ahvPaUsvV3nfJEee6LrPTw9P7S3/tei/BWhvBij/GVs/X7/P+SsfUnZeueufbg6fxul/I7c+02b+1Vhu+owffJ2fp8ofNKfe5Qge9plPGvxvj4+v4pZuuMrfT6+/4/de0oZeumv/dOgO+nwPcwa+z2+f6buPakvvf5+/4qZuvv9P6cuPazyPjq8P1Eeu7r8P2Pr/VThO+Ep/TP3PsmZOtjkPFkkPHT3/u+0fnR3vu2yvhCeO5ok/Ftl/JfjPDG1vpymvJ1nPL6+/+1yvgvauyMrPStxPeFqPS6zvkzbezZ5PwtaexXh/B+o/PU4Pva5PyJqvRwmPLl7f3Q3ftbifD8/f+GqPRJfe7y9v6RsPUybezB0/l/o/Pb5fy4zPhhjvGjvfdQgu+yyPi5zfm3y/jH1/rY4/uApPMmY+tBd+60yvjI2Pqdufaxx/ji6vwrZ+wuaexpSTgxAAACiElEQVR4nO3av0uUcQDH8c/neNIzsU7ICKGCMKLgCGmsiAaDhoqWcClyiqC5f6JN+gOcI2pwaKwtEMKhopR+UUgtktFgUGCDIF02hB++30Her+kZDj7c++65gy+PVYE3rta23Vqrwsa2RsBQI0kt+1eduR2WZHu1zpy007btlWIDjSTttpeLLfT4uWe509jufK4yN7qezyoccNjvxt4Um+gxvDyyKB1x51WNtY79QlLX//XqLWkkHbfHC078w5Cr7B0dWlmQpOfj5TZakgZezvf3d8ttbHKy3Z6rsTMyt2/9Yr7cRksabZ/SwNO95TZ6HZg493ZwsMrUoMrvNNK4fcEXq93DHxd12Z/OP6ow9Wz9J76oltRuS2t9r68U39rw8MGhKrfwd30tvtHS5JP7s7OzzUL5D+sPzYkaK6tnDp6VJF0tt9Gor0+Svlyr+T885f1VdsZ8WI+lGwXfm2/aviudfr90y9OlRjauru+anjhm275TaKv3MOG27ZkpzyxVWCuo53yke8k/ytXbdBrT/Tb54V6VtSojHGfhLwQMETBEwBABQwQMETBEwBABQwQMETBEwBABQwQMETBEwBABQwQMETBEwBABQwQMETBEwFCdR0W3Mb6BIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBgiYIiAIQKGCBj6DXnTRWuzaITHAAAAAElFTkSuQmCC)

![Flexbox at 210 pixels wide: two items in the first row and one in the second](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANIAAAB4CAMAAACwwFz4AAABelBMVEUlY+v///88c+2gu/Zjj/FaifCNrfWIqvR2nfJDeO6LrPTw9P7S3/tei/BWhvBij/GVs/X7/P+SsfXJ2fp8ofNKfe5Qge9plPGvxvj4+v4pZutOgO+nwPcwa+z2+f6buPakvvf5+/4qZuucuPazyPjq8P0oZetEeu7r8P2Pr/UnZevP3PsmZOtjkPFkkPHT3/u+0fnR3vu2yvhCeO5fjPDG1vpym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UUfOW65kiwAAAABJRU5ErkJggg==)

## Variations

### Let the last item grow

Replace the HTML-loading line in the full program:

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

The full program then prints:

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

## Related recipes

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

## The short answer

Render the same HTML twice with different `HtmlRenderOptions.Width` values. Put `display:flex` and `flex-wrap:wrap` on the container and give its children a usable basis. Save each returned image as PNG. To check that the layout really changed, create an `InteractivePage` at each width and query the child rectangles before painting.

The example is intentionally responsive without a media query. Its three items fit into one row at 320 pixels. At 210 pixels, the third item moves to a second row. The images and printed positions come from separate layouts of the same input, not from scaling one image.

## How do I wrap elements in CSS flex?

Enable wrapping on the parent, not on each item. Here the parent also has a 10-pixel gap. Each child uses `flex:0 0 100px`: no growth, no shrinkage and a 100-pixel starting size. Three items plus two gaps require 320 pixels. A width of 210 holds only two items plus one gap, so the third begins the next line.

The full program prints C at (220,0) for the wide layout and at (0,50) for the narrow layout. Its height is 40 pixels, so that 50-pixel row step includes the vertical gap. Setting body margin to zero keeps these coordinates relative to the image origin rather than an inset document body.

The [flex layout documentation](https://github.com/recursive-ai-oss/onerender-csharp/blob/d9708ace1863cae70a1b0782b8363ed970e555bb/docs/architecture.md#flex-layout-layoutflex-blocklayoutengineflexcs) describes support for direction, wrapping, basis, growth, shrinkage, order and alignment. This recipe uses a small subset so the wrap threshold is predictable. For the CSS model itself, see the [flexbox guide](https://css-tricks.com/snippets/css/a-guide-to-flexbox/).

## Does flex basis override width?

For this task, give the flex basis explicitly instead of relying on a width declaration. The basis is the starting main-axis size before flexible space is distributed; growth, shrinkage and minimum or maximum sizes can still affect the final rectangle. A declared basis is not a guarantee that every item will finish at that size.

The variation changes only the growth factor, from zero to one. At 320 pixels there is no spare horizontal space, so each item stays 100 pixels wide. At 210 pixels the lone item on the second row grows to 210 pixels. Its line is resolved separately from the first line. This is useful for cards that should fill a final row, but it is not the same as aligning every row into shared grid columns.

## How do I render flexbox to PNG in C#?

Choose the viewport before layout, then encode the resulting pixels. The snippet at the top is enough when only images are needed. The full program adds geometry queries to make the responsive behavior visible in text. It uses the same width for `HtmlPageOptions.ViewportWidth` and the raster output, so the PNG corresponds to the queried layout.

Increasing output pixel density is different from changing viewport width: the former adds pixels while the latter can change line breaks. Likewise, changing an image file’s dimensions afterward does not rerun flex layout. For a responsive preview, render again at the intended viewport.

OneRender does not execute JavaScript. If your application uses a script to add cards or toggle classes, build that final HTML before rendering it. Keep enough output height for wrapped rows; a viewport clips content rather than automatically growing to fit the whole document. In this example, 120 pixels includes both rows at the narrow width.
