---
title: "How to Create an Animated Social Preview with HTML and CSS"
description: "Create a short MP4 and a matching Open Graph image from one HTML design using the HTML/CSS to Image API, then add them to your page."
published: "2026-11-18"
author: "Jeffrey Needles"
canonical: "https://htmlcsstoimage.com/blog/create-animated-social-preview"
---


If you already make social cards with HTML and CSS, you can use the same approach for a short video. Add a CSS animation, record it as an MP4, then render the design again as a still image.

We'll make a product announcement for a fictional app called Orbit. The chart moves, but the headline stays visible. Both versions work on their own, which matters because some apps can play an `og:video` preview and others will show the `og:image` instead. The [guide to adding og:video](/blog/add-open-graph-video) covers those differences and the hosting requirements.

Here's the video we'll create with the HTML/CSS to Image API:

[A four-second product announcement for Orbit, with a gently moving dashboard and animated chart bars](https://content-images.htmlcsstoimage.com/media-assets/4450e04d789fb08e2419182d25041f7bbd883a33c14bf75268b47869b99a5cef/animated-social-preview.mp4){autoplay loop}

## TL;DR: Create an Animated Social Preview

1. Design a card whose headline and illustration are visible before any animation starts.
2. Put its CSS animations behind a class, then add that class when recording begins.
3. Record a short MP4 at an explicit viewport size with `device_scale: 1` and `duration_mode: "fixed"`.
4. Render a PNG from the same HTML without starting the animation.
5. Wait for the recording to be ready, then put the video and image URLs in the page's Open Graph tags.

You'll need Node.js 18 or newer and an HTML/CSS to Image account with recordings enabled. Recordings are available on the Startup plan and above. See the [recordings documentation](https://docs.htmlcsstoimage.com/getting-started/recordings/){target=_blank} for current availability and credit usage.

## 1. Make a Card That Also Works as a Still

[Download the example HTML](https://content-images.htmlcsstoimage.com/media-assets/30ec82bc0422583a748b1294ef7bd625e3ac941137404314b7215a37ce9e7ba7/animated-social-preview.html) and save it as `animated-social-preview.html`. It includes all the CSS and uses a system font, so there are no external assets to load.

The layout is 1200 × 630 pixels. That is a convenient size for this wide social card, rather than a requirement imposed by `og:video`:

```css
* { box-sizing: border-box; }
body { margin: 0; }
main {
  width: 1200px;
  height: 630px;
  padding: 64px;
  overflow: hidden;
}
```

Open the file in a browser. The headline, dashboard and chart should already be visible. This is the design we'll use for the poster:

![The static Orbit announcement, with the complete headline and dashboard illustration visible](https://content-images.htmlcsstoimage.com/media-assets/4e002b9f2fb9500145c8b7490e6c43070ab9dfdeea2092fa11bef79bb977a592/animated-social-preview.png)

Keep the important content away from the edges and use large text. A card that looks spacious at full size can become hard to read inside a message. Put the announcement title in `og:title` too, so the meaning does not depend entirely on text baked into an image.

### Start the Animation When Recording Begins

The downloaded example only animates when the body has a `recording` class:

```css
.recording .bar { animation: chart 4s ease-in-out infinite; }
.recording .dashboard { animation: float 4s ease-in-out infinite; }

@keyframes chart {
  0%, 100% { transform: scaleY(1); }
  50% { transform: scaleY(var(--low)); }
}

@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}
```

Each bar has its own `--low` value, so they move by different amounts. The animation returns to its starting position after four seconds. That makes the clip suitable for looping on your own site, although the app displaying a shared link controls its own playback behavior.

If the animation starts as soon as the HTML loads, some of it can run while the renderer is preparing the page. We'll add the class with an API action instead. The poster request will leave it off.

## 2. Record the MP4 with the HTML/CSS to Image API

Install the [official JavaScript client](https://docs.htmlcsstoimage.com/example-code/typescript/){target=_blank}:

```bash
npm install @html-css-to-image/client
```

Set `HCTI_API_ID` and `HCTI_API_KEY` in your server environment. Keep these credentials on the backend, outside any code delivered to visitors.

[Download the complete rendering script](https://content-images.htmlcsstoimage.com/media-assets/da68ab7ac20c3938f4b63fd964292f0426e75feab3213720da0baf48cda8a92e/render-social-preview.mjs) and save it beside the HTML file as `render-social-preview.mjs`. The next three sections explain its recording, poster and readiness steps.

This part reads the HTML and creates a recording with the typed request class:

```js
import { readFile } from "node:fs/promises";
import { setTimeout } from "node:timers/promises";
import {
  HtmlCssToImageClient,
  CreateHtmlCssRecordingRequest,
  CreateHtmlCssImageRequest,
} from "@html-css-to-image/client";

const client = HtmlCssToImageClient.fromEnv();
const html = await readFile(
  new URL("./animated-social-preview.html", import.meta.url),
  "utf8",
);

const video = await client.createRecording(
  new CreateHtmlCssRecordingRequest({
    html,
    viewport_width: 1200,
    viewport_height: 630,
    device_scale: 1,
    duration_ms: 4000,
    duration_mode: "fixed",
    actions: [
      {
        type: "execute_javascript",
        script: "document.body.classList.add('recording');",
      },
    ],
    output: { format: "mp4", fps: 30 },
  }),
);

if (!video.success) throw new Error(JSON.stringify(video));
```

The renderer captures the whole viewport, so the viewport matches the card. `device_scale: 1` keeps the output at 1200 × 630 physical pixels. The action adds the class as capture begins.

> [!TIP]
> Use `duration_mode: "fixed"` here. The default mode can end when the actions finish, and adding a class finishes almost immediately. Fixed mode keeps recording for the full four seconds while the CSS animation runs.

MP4 at 30 fps is enough for this animation. HCTI recordings have no audio, so make sure the preview communicates what you need visually. The [output reference](https://docs.htmlcsstoimage.com/parameters/output/){target=_blank} covers formats, frame rates and scaling.

For a design that loads data or draws a chart with JavaScript, use a [readiness trigger](https://docs.htmlcsstoimage.com/parameters/trigger/){target=_blank} before starting the animation. This example has no loading step to wait for.

## 3. Render the Matching Open Graph Image

The script sends the same HTML to the image endpoint:

```js
const poster = await client.createImage(
  new CreateHtmlCssImageRequest({
    html,
    selector: "main",
    viewport_width: 1200,
    viewport_height: 630,
    device_scale: 1,
    format: "png",
  }),
);

if (!poster.success) throw new Error(JSON.stringify(poster));
```

This is a separate render. It does not inherit the `recording` class added during the video request, so the chart stays in its original position. The `main` selector captures exactly the card.

For a more elaborate animation, design an explicit poster state. If your video begins with an empty canvas and reveals the title later, the unanimated page would make a poor thumbnail. You can pass extra CSS in the image request to make the title and illustration visible.

## 4. Wait for the Video Before Publishing the Tags

The recording creation response includes a media URL before the MP4 is finished. For a social preview, wait until it is ready before publishing it. That avoids making the first preview request wait for video generation.

The complete script checks status every two seconds, with a two-minute limit for this example:

```js
async function waitForRecording(id) {
  const deadline = Date.now() + 120_000;

  while (Date.now() < deadline) {
    const result = await client.fetchRecordingStatus(id);
    if (!result.success) throw new Error(JSON.stringify(result));
    if (result.status === "ready") return result;
    if (!["processing", "pending_retry"].includes(result.status)) {
      throw new Error(JSON.stringify(result));
    }
    await setTimeout(2000);
  }

  throw new Error("Recording is still processing. Check its status again later.");
}

await waitForRecording(video.id);

console.log("og:video:", video.recording_url);
console.log("og:image:", poster.url);
```

Run the downloaded script:

```bash
node render-social-preview.mjs
```

It prints the two URLs to put in your metadata. If a recording is still processing when the script stops waiting, check that recording's status again rather than immediately creating another one. For a production publishing workflow, you can use the [`recording_stored` webhook](https://docs.htmlcsstoimage.com/management-api/recordings/){target=_blank} instead of keeping a process waiting.

## 5. Add the Video and Image to Your Page

Keep your page's existing title, description, `og:type` and `og:url`. Add the two media resources, using the URLs printed by the script:

```html
<meta property="og:image" content="https://your-public-media.example/preview-v1.png">
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="The new Orbit dashboard with a weekly activity chart.">

<meta property="og:video" content="https://your-public-media.example/preview-v1.mp4">
<meta property="og:video:type" content="video/mp4">
<meta property="og:video:width" content="1200">
<meta property="og:video:height" content="630">
```

The placeholder domain above stands for your returned HCTI URLs or your own public media host. You do not need to download and rehost files that HCTI is already hosting for you. If you use a storage destination with HCTI hosting disabled, use that destination's public media URLs instead.

Serve these tags in the page's initial HTML. Share the page in the apps you care about and confirm that the image works when the video is not displayed. Apple Messages documents support for direct video assets, but that does not establish playback support in another app. The [technical og:video guide](/blog/add-open-graph-video) includes the download and byte-range checks.

## 6. Reuse the Design for the Next Announcement

Change the headline, colors or illustration in the HTML and run the script again. Generate both files from that updated markup so an image-only preview does not show a different announcement from the video.

Store the finished URLs with the page and reuse them. Generate the assets when content changes, rather than on each page visit. When you update a published preview, use new media URLs and update the tags together. See [fixing an outdated Open Graph image](/blog/fix-outdated-open-graph-image) if an app keeps showing the previous version.

You can also use the MP4 in a native social post or on your own website. Those are separate uses of the same file, and do not depend on a link-preview app supporting `og:video`.

## Frequently Asked Questions

#### Will This Make Every Social Link Preview Animated?

No. The receiving app decides whether to use the video, show an image or require a tap. Always publish a useful image fallback and test the actual shared page.

#### Can I Create an Animated Social Preview Without Installing a Browser?

Yes. The script runs in Node.js, but the browser that renders the HTML runs on HTML/CSS to Image's servers. You do not need to install Chromium or manage a screen-recording process.

#### Can I Use My Existing HTML Social Card?

Yes. Make its dimensions explicit, add an animation and start it with an action. Keep a static state for `og:image`. If you need help generating the still first, see [converting HTML to an image in JavaScript](/blog/convert-html-to-image-javascript).

#### Can I Export a GIF Too?

Yes. Create another recording request with `output: { format: "gif", fps: 15 }`. That can be useful in a blog post or README, but a GIF does not make every app's Open Graph preview animate. For the metadata in this tutorial, keep the MP4 and PNG pair.

#### Can an AI Assistant Make the HTML and Record It?

Yes. An assistant connected to the [HTML/CSS to Image MCP server](https://docs.htmlcsstoimage.com/integrations/mcp/tools/#recordings){target=_blank} can create the design, call `create_htmlcss_recording`, check the recording status and render the matching image. Ask it to inspect both outputs before you publish. The [recordings announcement](/blog/recordings-html-css-to-video) has more examples of what the API can capture.
