webdevpuneet.com

Metric KPI Card Grid — Animated Dashboard Cards HTML CSS JS

Metric KPI Card Grid · Dashboards · Plain HTML, CSS & JS · Live preview

CategoryDashboards

About this UI Snippet

Metric KPI Card Grid — Smooth Sparklines, Count-Up Numbers & Dashboard Layout Pattern

Screenshot of the Metric KPI Card Grid snippet rendered live

KPI metric cards are the centrepiece of every analytics dashboard — they surface the numbers that matter most and show direction (up, down, flat) at a glance. This snippet builds a complete dashboard overview: four metric cards with count-up values, smooth SVG area sparklines you can hover for exact values, good/bad-aware trend badges, a sliding period toggle that really swaps the data, and two breakdown panels (channel share and goal progress) whose bars animate to their new widths. It follows the system light/dark preference with no extra code.

The design challenge is information density. Each card has to carry a value, a direction, the size of the change and a trend over time without feeling crowded. The icon tile, trend pill and sparkline each add one signal layer, and the big tabular-number value stays the loudest thing on the card.

Smooth sparklines from one data array

Every card's sparkline is generated from a plain array in the PERIODS object. The script normalises the points between that series' own min and max, converts them to a Catmull-Rom spline (a series of cubic Bézier curves) and draws it as an SVG path with a soft gradient area underneath. The SVG uses preserveAspectRatio="none" so it stretches to any card width, and vector-effect: non-scaling-stroke keeps the line a constant 2px instead of getting squashed. On every redraw the chart wipes in from left to right with an animated clip-path.

Hover, touch and tooltips without a library

A single pointermove handler maps the cursor's x position to the nearest data index, then moves an HTML dot, a crosshair line and a tooltip to that point. The dot and tooltip are normal elements positioned by percentage, so they stay perfectly round even though the SVG underneath is stretched. Because it uses pointer events, the same code works for mouse, pen and touch.

Count-up values and a working period toggle

Switching 30d / 7d / 24h doesn't just move a highlight — render() reads the new period's data, counts every number from its previous value to the new one with requestAnimationFrame and an ease-out curve, redraws the sparklines and animates the breakdown bars to their new widths. The active pill is a single absolutely positioned element that slides using a --i custom property, so the motion is one CSS transform — the same idea as the segmented control, and the count-up follows the number ticker approach.

Trend badges that know good from bad

A trend badge combines an arrow, the percentage and a tinted background, so direction never relies on colour alone, and it carries an aria-label for screen readers. Direction and meaning are separate: the badge class is up/down from the sign, then good/bad from the metric's lowerIsBetter flag. A falling churn rate or page load time can therefore show a down arrow in green, while a falling session length shows a down arrow in red.

Theming and motion

All colours are CSS variables defined on :root with a prefers-color-scheme: dark override, and each card receives its accent through --c and --ct. Cards fade up with a staggered delay, a soft spotlight follows the cursor, and prefers-reduced-motion switches the animations off and shows final values immediately.

Need a bigger chart than a sparkline? Pair the grid with an area chart or a standalone sparkline chart, show goal health with a donut progress ring, or build a full draggable layout from the dashboard widget grid.

What's included

Features

Smooth SVG area sparklines
Catmull-Rom splines drawn as an SVG path with a gradient fill that scales to any card width and redraws with a left-to-right wipe animation on every period change.
Hover and touch tooltips
One pointer handler snaps a dot, crosshair and value tooltip to the nearest data point — mouse, pen and touch, with no chart library.
Count-up numbers
Values animate from their previous number to the new one with an ease-out curve, using locale formatting, currency and mm:ss time formatters.
Working period toggle
A segmented control with a sliding pill (one CSS custom property) that really re-renders cards, sparklines and breakdown bars from the data object.
Good/bad-aware trend badges
Arrow + percentage + tinted pill, with a lowerIsBetter flag so a falling churn rate is green and a falling revenue is red. Includes an aria-label.
Animated breakdown bars
Channel share and goal progress bars transition to new widths while their percentages count up, so a period change feels continuous.
Light and dark mode
Every colour is a CSS variable with a prefers-color-scheme: dark override, so the dashboard follows the visitor's system theme automatically.
Cursor spotlight and stagger
Cards rise in one after another and show a soft accent glow that follows the pointer. Reduced-motion users get final values with no animation.

Step by step

How to Use

  1. 1
    Paste HTML, CSS, and JSFour KPI cards fade in with counting values and wipe-in sparklines. Below them sit a channel breakdown and goal progress panel whose bars animate to their values.
  2. 2
    Read the metric cardsTotal Users (↑12.5%), Monthly Revenue (↑8.2%), Avg. Session (↓2.1%, shown red because shorter sessions are bad) and Conversion Rate (↑4.7%). Each card includes a spline sparkline of the period's trend.
  3. 3
    Hover or touch a sparklineA dot and crosshair snap to the nearest data point and a tooltip shows its label (Day 8, Hour 12…) and value. It works the same with a finger drag on touch screens.
  4. 4
    Switch the periodClick 30d, 7d or 24h. The pill slides across, every value counts to its new number, sparklines redraw and the breakdown bars animate to new widths — all from the PERIODS object.
  5. 5
    Replace the dataEdit the PERIODS object: v is the value, t the signed percentage change, d the sparkline points. For an API, fill PERIODS from your response and call render(period).
  6. 6
    Mark "lower is better" metricsFor churn, errors or latency, add lowerIsBetter: true to that metric in METRICS. A falling number then gets a green badge instead of red.

Real-world uses

Common Use Cases

SaaS analytics dashboards
The primary use case — user growth, revenue, activation and churn in the main overview. The period toggle drives the date range and every number animates to its new value.
E-commerce performance dashboards
Orders, revenue, conversion rate and average order value as headline metrics, with the channel panel showing where traffic comes from.
Marketing analytics overviews
Impressions, clicks, conversions and CPA as KPIs. Mark CPA as lowerIsBetter and use goal bars to show campaign pacing against monthly targets.
Executive reporting dashboards
High-level business numbers for leadership — a value, a direction and a trend line per metric, with no raw data tables needed.
DevOps monitoring dashboards
Requests per second, error rate, p95 latency and uptime. Hover the sparkline to read the exact hourly value; error rate and latency use lowerIsBetter.
Internal team productivity tools
Tickets closed, velocity, deployment frequency and cycle time — the DORA metrics overview, with a 7-day and 30-day view.
Related: Area Chart
Put a full area chart under the KPI cards for the detailed trend, and a dashboard widget grid around both for a draggable layout.

Got questions?

Frequently Asked Questions

The toggle already calls render(period), which reads from the PERIODS object. Fetch your metrics, fill PERIODS[period] in the same shape (value v, change t, points d), then call render. Cancel or ignore stale responses if users switch periods quickly.

Add lowerIsBetter: true to that metric inside METRICS, for example churn: { fmt: ..., lowerIsBetter: true }. The arrow still points down, but the badge gets the green good style instead of red.

Copy one <article class="metric-card" data-key="...">, give it a new data-key and accent colours, add a matching entry to METRICS and to each period in PERIODS. Then adjust the grid to repeat(auto-fit, minmax(190px, 1fr)) if you want it to wrap on its own.

A spline area line shows trend more clearly at small sizes and enables a snap-to-point hover. It uses one path per card, so it stays light. If you prefer bars, replace drawSpark with a function that creates one <div> per value sized by value / max.

Make a MetricCard with {label, value, change, data, color, icon, lowerIsBetter} props and a Sparkline that renders the SVG path from data. Keep the active period in useState, fetch in useEffect([period]), and reuse the count-up logic in a small useCountUp hook.

Copy & paste

Source Code

<div class="page">
  <header class="page-header">
    <div>
      <h1 class="page-title">Overview</h1>
      <p class="page-sub"><span class="live-dot" aria-hidden="true"></span><span id="periodLabel">Last 30 days</span> · Updated just now</p>
    </div>
    <div class="period-toggle" role="group" aria-label="Time period" style="--i:0">
      <span class="pt-ind" aria-hidden="true"></span>
      <button class="pt-btn active" type="button" data-period="30d" aria-pressed="true">30d</button>
      <button class="pt-btn" type="button" data-period="7d" aria-pressed="false">7d</button>
      <button class="pt-btn" type="button" data-period="1d" aria-pressed="false">24h</button>
    </div>
  </header>

  <section class="metric-grid" aria-label="Key metrics">
    <article class="metric-card" data-key="users" style="--c:#6366f1;--ct:rgba(99,102,241,.14);--n:0">
      <div class="metric-top">
        <div class="metric-icon">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
        </div>
        <span class="trend up"><span class="trend-arrow" aria-hidden="true">↑</span><span class="trend-val">12.5%</span></span>
      </div>
      <div class="metric-val">24,531</div>
      <div class="metric-label">Total Users</div>
      <div class="spark"></div>
    </article>

    <article class="metric-card" data-key="revenue" style="--c:#10b981;--ct:rgba(16,185,129,.14);--n:1">
      <div class="metric-top">
        <div class="metric-icon">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
        </div>
        <span class="trend up"><span class="trend-arrow" aria-hidden="true">↑</span><span class="trend-val">8.2%</span></span>
      </div>
      <div class="metric-val">$48,290</div>
      <div class="metric-label">Monthly Revenue</div>
      <div class="spark"></div>
    </article>

    <article class="metric-card" data-key="session" style="--c:#f59e0b;--ct:rgba(245,158,11,.16);--n:2">
      <div class="metric-top">
        <div class="metric-icon">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
        </div>
        <span class="trend down"><span class="trend-arrow" aria-hidden="true">↓</span><span class="trend-val">2.1%</span></span>
      </div>
      <div class="metric-val">3m 42s</div>
      <div class="metric-label">Avg. Session</div>
      <div class="spark"></div>
    </article>

    <article class="metric-card" data-key="conv" style="--c:#a855f7;--ct:rgba(168,85,247,.14);--n:3">
      <div class="metric-top">
        <div class="metric-icon">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
        </div>
        <span class="trend up"><span class="trend-arrow" aria-hidden="true">↑</span><span class="trend-val">4.7%</span></span>
      </div>
      <div class="metric-val">73.4%</div>
      <div class="metric-label">Conversion Rate</div>
      <div class="spark"></div>
    </article>
  </section>

  <section class="breakdown-row">
    <div class="breakdown-card">
      <h3 class="breakdown-title">Top Channels</h3>
      <div class="channel-list">
        <div class="channel-item">
          <span class="ch-name"><i style="background:#6366f1"></i>Organic Search</span>
          <div class="ch-bar-wrap"><div class="ch-bar" style="background:#6366f1"></div></div>
          <span class="ch-pct">68%</span>
        </div>
        <div class="channel-item">
          <span class="ch-name"><i style="background:#10b981"></i>Direct</span>
          <div class="ch-bar-wrap"><div class="ch-bar" style="background:#10b981"></div></div>
          <span class="ch-pct">22%</span>
        </div>
        <div class="channel-item">
          <span class="ch-name"><i style="background:#f59e0b"></i>Social</span>
          <div class="ch-bar-wrap"><div class="ch-bar" style="background:#f59e0b"></div></div>
          <span class="ch-pct">10%</span>
        </div>
      </div>
    </div>
    <div class="breakdown-card">
      <h3 class="breakdown-title">Goal Progress</h3>
      <div class="goals">
        <div class="goal-item">
          <div class="goal-head"><span>Revenue target</span><span class="goal-pct">82%</span></div>
          <div class="goal-track"><div class="goal-fill" style="background:linear-gradient(90deg,#6366f1,#8b5cf6)"></div></div>
        </div>
        <div class="goal-item">
          <div class="goal-head"><span>User growth</span><span class="goal-pct">91%</span></div>
          <div class="goal-track"><div class="goal-fill" style="background:linear-gradient(90deg,#10b981,#059669)"></div></div>
        </div>
        <div class="goal-item">
          <div class="goal-head"><span>Churn reduction</span><span class="goal-pct">44%</span></div>
          <div class="goal-track"><div class="goal-fill" style="background:linear-gradient(90deg,#f59e0b,#ef4444)"></div></div>
        </div>
      </div>
    </div>
  </section>
</div>

Extend with AI

Take This Snippet Further With AI

You don't need to eyeball the spline or count-up math to trust it. Paste this snippet's HTML, CSS, and JS into an AI coding assistant like Claude and ask it to explain how the Catmull-Rom points become cubic Bézier segments, why each sparkline is normalised to its own min and max, or why the tooltip is an HTML element instead of an SVG circle inside a stretched viewBox. It's also a good partner for hardening it — asking whether redrawing every sparkline on each period click causes layout work you could avoid, how to cancel a count-up that is still running when the user switches period again, or how to handle a real API response that arrives out of order. And it's a fast way to extend it: add a fifth card with a "lower is better" metric, compare against the previous period with a dashed second line, or sync the tooltip across all four sparklines at once. Treat the code as the start of a conversation, not a finished artifact.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build an animated "KPI metric card grid" analytics dashboard overview as ONE self-contained HTML file (inline CSS and JS, no frameworks, no charting library, no external requests). It should look like a polished SaaS product, in both light and dark themes.

DATA MODEL (single source of truth)
- One JavaScript object PERIODS keyed '30d', '7d', '1d'. Each period has: a label ("Last 30 days"), a tooltip unit ("Day"/"Hour") and step, four metrics {v: value, t: signed % change vs previous period, d: array of 7-12 sparkline points}, plus channels [3 percentages] and goals [3 percentages].
- Metrics: Total Users (24,531, +12.5%), Monthly Revenue ($48,290, +8.2%), Avg. Session (3m 42s, -2.1%), Conversion Rate (73.4%, +4.7%). Per-metric formatter functions: thousands separators, currency, minutes+seconds, one-decimal percent. A per-metric lowerIsBetter flag (default false).
- One render(period) function updates every number, sparkline, badge and bar from this object, so wiring a real API means filling PERIODS and calling render().

LAYOUT
- Header: "Overview" title, a pulsing green live dot with "<period label> · Updated just now", and a segmented period toggle (30d / 7d / 24h) on the right.
- A CSS grid of four metric cards: 4 columns, 2 columns under 820px, 1 column under 380px. Each card (16px radius, 1px border, soft shadow): 36px tinted icon tile with an inline SVG icon, trend badge, 26px bold tabular-number value, small label, then a 46px-tall sparkline. Accents: indigo #6366f1, emerald #10b981, amber #f59e0b, purple #a855f7, exposed as CSS custom properties (--c solid, --ct tinted) on each card.
- Below: two cards side by side (stacked under 620px): "Top Channels" (colour dot, label, thin bar, percentage) and "Goal Progress" (label row with percentage, then a 9px gradient bar: indigo→violet, emerald, amber→red).

SPARKLINES (inline SVG, generated by JS)
- viewBox 0 0 120 40, preserveAspectRatio="none", vector-effect: non-scaling-stroke so the 2px line never distorts. Normalise points to that series' own min and max with padding.
- Smooth the line with a Catmull-Rom spline converted to cubic Bézier segments; add a gradient area fill (accent colour, 28% opacity fading to 0).
- On every redraw, wipe the chart in left to right with an animated clip-path (about 0.9s ease).
- Hover and touch via ONE pointermove/pointerdown handler: snap to the nearest data point and show a dot, a vertical crosshair, and a dark tooltip containing a label (e.g. "Day 8") plus the formatted value. Make the dot and tooltip absolutely positioned HTML elements placed by percentage so the dot stays perfectly round despite the stretched SVG. Hide on pointerleave.

MOTION AND INTERACTION
- Numbers count from their previous value to the new one with requestAnimationFrame and ease-out cubic over about 900ms; cancel any running count on the same element before starting a new one.
- Cards fade up on load with a staggered animation-delay. A soft radial accent glow follows the cursor inside each card (--mx / --my set on pointermove) and cards lift 3px on hover.
- The period toggle has ONE absolutely positioned sliding pill driven by a --i custom property (transform: translateX(calc(var(--i) * 100%))), buttons with aria-pressed, and a click re-renders everything. Channel and goal bars animate width through CSS transitions while their percentages count up.
- Respect prefers-reduced-motion: no animation, final values immediately.

TREND BADGES
- Pill with arrow + percentage + tinted background, never colour alone, plus an aria-label like "Up 12.5 percent". Direction comes from the sign of t (up/down); meaning comes from lowerIsBetter (good = green, bad = red). So Avg. Session -2.1% shows a red down arrow, while a lowerIsBetter metric falling shows a green down arrow.

THEMING AND QUALITY
- All colours as CSS variables on :root with a prefers-color-scheme: dark override (background, card, border, text levels, bar tracks, badge colours, tooltip). Use font-variant-numeric: tabular-nums on all figures.
- Semantic markup (header, section, article), visible focus rings on the toggle, a plain reset (box-sizing, zero margins) and a body background from the theme variable, and no console errors.

Return only the finished single HTML file.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.