---
title: "Resize a live HTML viewport and set device pixel ratio in C#"
url: https://recursiveai.org/onerender/cookbook/resize-live-page-and-set-pixel-ratio/
description: "Resize an existing HTML viewport and set its device pixel ratio in C# with OneRender. Repaint at the new size without losing the current form value."
version: "1.6.1"
---

# Resize a live HTML viewport and set device pixel ratio 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/resize-live-page-and-set-pixel-ratio/resize-live-page-and-set-pixel-ratio.zip)

Call `SetViewport(width, height, ratio)` on the existing page to keep its form values.

```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.

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

var page = InteractivePage.Create(
    "<input id='name' value='Draft'>",
    new HtmlPageOptions(
        FontProviders.CreateDefault()));
var input = page.FindElement("name");
page.SetValue(input, "Edited");
page.SetViewport(320, 180, 2);
Console.WriteLine(
    page.GetValue(page.FindElement("name")));
```

```text
Edited
```

The input keeps its edited value. The full program below shows the effect of 2×: a 320 × 180 CSS-pixel viewport produces a 640 × 360-pixel `after.png`.

[The example](https://recursiveai.org/onerender/cookbook/resize-live-page-and-set-pixel-ratio/resize-live-page-and-set-pixel-ratio.zip) is the full program below: unzip it and `dotnet run`. To run only the code above, paste it into Program.cs of a new `dotnet new console` project and `dotnet run`.

## The full program

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

const string html = """
    <style>
      #card { width: 50vw; background: #dcecfb; padding: 8px }
      input { width: 100%; box-sizing: border-box }
      @media (max-width: 320px) and (min-resolution: 2dppx) {
        #card { background: #b9ecd3 }
      }
    </style>
    <div id="card"><input id="name" value="Draft"></div>
    """;
var page = InteractivePage.Create(html,
    new HtmlPageOptions(FontProviders.CreateDefault())
    { ViewportWidth = 480, ViewportHeight = 100 });
page.SetValue(page.FindElement("name"), "Edited");
Save("before.png");
page.SetViewport(320, 180, 2);
Save("after.png");
Console.WriteLine($"Input: {page.GetValue(page.FindElement("name"))}");

void Save(string path)
{
    double width = page.ViewportWidth;
    double height = page.ViewportHeight;
    float ratio = (float)page.DevicePixelRatio;
    var drawing = new DisplayList();
    page.Page.Paint(drawing);
    int pixelsWide = (int)Math.Ceiling(width * ratio);
    int pixelsHigh = (int)Math.Ceiling(height * ratio);
    var image = DisplayListRasterizer.Render(drawing, pixelsWide, pixelsHigh,
        new RasterOptions { DevicePixelRatio = ratio });
    File.WriteAllBytes(path, image.ToPng());
    Console.WriteLine($"{path}: {width}x{height} CSS px at {ratio}x"
        + $" -> {image.Width}x{image.Height} pixels");
}
```

```text
before.png: 480x100 CSS px at 1x -> 480x100 pixels
after.png: 320x180 CSS px at 2x -> 640x360 pixels
Input: Edited
```

The blue card becomes green when the width and resolution conditions both match. The input still reads “Edited”, not the markup’s initial value “Draft”.

A width or height below 1 CSS pixel, or a zero or negative ratio, throws `ArgumentOutOfRangeException` and leaves the viewport unchanged.

## Variations

**Handle separate window and display events.** Replace `SetViewport` with these calls if the size and ratio arrive separately:

```csharp
page.Resize(360, 180);       // keeps the current ratio
page.SetDevicePixelRatio(2); // keeps the current size
```

## Related recipes

- [Insert and remove HTML elements on a live page in C#](https://recursiveai.org/onerender/cookbook/insert-remove-elements-on-live-html-page/)
- [Render HTML to PNG in C#](https://recursiveai.org/onerender/cookbook/html-to-png/)

## The short answer

Call `page.SetViewport(width, height, ratio)` on the `InteractivePage` you already have. Pass dimensions in CSS pixels and the device pixel ratio separately. Then paint the current page and resize the target bitmap to match its new physical pixel dimensions.

## How do I set the viewport size of an HTML render?

For an interactive page, `Resize` changes the CSS viewport size, `SetDevicePixelRatio` changes just the pixel ratio, and `SetViewport` changes both together. These methods configure OneRender’s viewport, not the operating system window. Use the window size your host reports in CSS pixels or convert from physical pixels first; otherwise the layout can pick a wide-screen breakpoint on a narrow high-density window.

The CSS viewport determines what `vw` means. In the example, `50vw` is 240 CSS pixels before resizing and 160 after, not counting padding. OneRender rechecks media queries that depend on width, height, aspect ratio, orientation or resolution. The green card requires both a width of at most 320 CSS pixels and a resolution of at least 2 device pixels per CSS pixel.

## What is a device pixel ratio?

[Device pixel ratio](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio) is how many physical pixels cover one CSS pixel along an axis. At 2×, a box that’s 100 CSS pixels wide uses 200 bitmap pixels. When rasterizing, size the bitmap and pass the same ratio to `RasterOptions.DevicePixelRatio`. Increasing the bitmap dimensions without setting the rasterizer’s ratio doesn’t scale the drawing to fill that bitmap. A ratio change also affects snapping to pixel edges and may change layout if a resolution query changes which rules apply.

## Will resizing the HTML viewport reset form fields?

Not when you resize the existing `InteractivePage`. The [viewport documentation](https://recursiveai.org/onerender/docs/game-hosts/#resizing-the-window-and-changing-the-device-pixel-ratio) says the page keeps form values and selection, listeners and running animations. The example finds the same input after resizing and reads its current value rather than the initial `value` attribute. There are layout-dependent exceptions for interaction: a focused element that a media query hides loses focus, and the new scroll range can clamp a scroll position. Handle those as changes to the live page, not as a reason to reload the HTML.
