Skip to content

CSS Gradient Generator — TypeScript source

Build linear, radial, and conic CSS gradients with multiple color stops and positions. Live preview and copy-ready CSS.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure CSS-gradient builder - no React, no DOM, deterministic.
// Builds linear/radial/conic gradient strings. Never throws.

export type GradientType = 'linear' | 'radial' | 'conic';

export interface GradientStop {
  color: string;
  position: number; // 0..100
}

export interface GradientConfig {
  type: GradientType;
  angle: number; // degrees
  stops: GradientStop[];
  radialShape?: 'circle' | 'ellipse';
}

const NAMED_COLORS = new Set([
  'transparent', 'black', 'white', 'red', 'green', 'blue', 'yellow',
  'orange', 'purple', 'pink', 'gray', 'grey', 'brown', 'cyan', 'magenta',
  'none', 'currentcolor',
]);

export function parseColor(color: string): { ok: boolean; error: string | null } {
  const c = (color || '').trim().toLowerCase();
  if (!c) return { ok: false, error: 'empty color' };
  if (NAMED_COLORS.has(c)) return { ok: true, error: null };
  if (/^#[0-9a-f]{3}([0-9a-f]{3})?$/.test(c)) return { ok: true, error: null };
  if (/^#[0-9a-f]{8}$/.test(c)) return { ok: true, error: null };
  if (/^rgba?\([^)]+\)$/.test(c)) return { ok: true, error: null };
  if (/^hsla?\([^)]+\)$/.test(c)) return { ok: true, error: null };
  return { ok: false, error: `invalid color: ${color}` };
}

function normalizeColor(color: string): string {
  const { ok } = parseColor(color);
  return ok ? color.trim() : '#000000';
}

export function buildGradient(config: GradientConfig): string {
  let stops = [...config.stops].sort((a, b) => a.position - b.position);
  // Drop nonsensical entries; pad if fewer than 2.
  if (stops.length < 2) {
    stops = [
      { color: '#000000', position: 0 },
      { color: '#ffffff', position: 100 },
    ];
  }
  const stopsStr = stops
    .map((s) => `${normalizeColor(s.color)} ${Math.round(s.position)}%`)
    .join(', ');

  switch (config.type) {
    case 'linear':
      return `linear-gradient(${config.angle}deg, ${stopsStr})`;
    case 'radial':
      return `radial-gradient(${config.radialShape ?? 'circle'}, ${stopsStr})`;
    case 'conic':
      return `conic-gradient(from ${config.angle}deg, ${stopsStr})`;
  }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →