Skip to content

Accessibility (WCAG)

bestGradientTextColor

Returns '#000000' or '#ffffff' — whichever achieves the best minimum contrast across all gradient stops.

ts
import { bestGradientTextColor } from 'css-magic-gradient'

// Two-color gradient (backward-compatible)
bestGradientTextColor('#1a1a2e', '#e94560')
// → '#ffffff'

// Multi-stop gradient
bestGradientTextColor(['#1a1a2e', '#c0357a', '#e94560'])
// → '#ffffff'

// Detailed result with per-color scores
const detail = bestGradientTextColor(['#1a1a2e', '#e94560'], { detailed: true })
// → { recommended: '#ffffff', black: { contrast: 1.8, wcag: 'fail' }, white: { contrast: 9.3, wcag: 'AAA' } }

gradientContrastRatio

Returns the minimum WCAG contrast ratio of a text color against the gradient. Samples 11 evenly distributed points along the gradient.

ts
import { gradientContrastRatio } from 'css-magic-gradient'

// Two colors (backward-compatible)
gradientContrastRatio('#ffffff', '#1a1a2e', '#e94560')
// → minimum ratio across all sampled points

// Array of stops
gradientContrastRatio('#ffffff', ['#1a1a2e', '#c0357a', '#e94560'])

gradientWcagLevel

Returns a detailed GradientWcagReport with the worst-case WCAG level, minimum contrast, and positions that fail the AA threshold.

ts
import { gradientWcagLevel } from 'css-magic-gradient'

const report = gradientWcagLevel('#ffffff', '#1a1a2e', '#e94560')
// → {
//     level: 'AAA',
//     minContrast: 8.4,
//     problematicStops: []   // positions (0–1) where contrast < 4.5
//   }

// With a gradient that has a weak midpoint:
const report2 = gradientWcagLevel('#ffffff', ['#ffffff', '#aaaaaa', '#3498db'])
// → { level: 'fail', minContrast: 1.07, problematicStops: [0, 0.09, 0.18, …] }

GradientWcagReport

FieldTypeDescription
levelWcagLevelWorst WCAG level found across all sampled stops
minContrastnumberMinimum contrast ratio along the gradient
problematicStopsnumber[]Fractional positions (0–1) where contrast < 4.5

createAccessibleGradient

Auto-adjusts gradient stops until textColor achieves the target WCAG level.

ts
import { createAccessibleGradient } from 'css-magic-gradient'

// Default: adjusts lightness in 5% steps until AA is met
createAccessibleGradient('#3498db', '#ffffff', {
  targetLevel: 'AA',
})

// Adjust saturation instead
createAccessibleGradient('#3498db', '#ffffff', {
  targetLevel: 'AAA',
  adjustmentStrategy: 'saturation',
})

// Adjust both lightness and saturation
createAccessibleGradient('#c0357a', '#000000', {
  adjustmentStrategy: 'both',
  direction: 'to right',
})

AccessibleGradientOptions

OptionTypeDefaultDescription
directionstring'to bottom'CSS direction keyword
anglenumberAngle in degrees
targetLevel'AAA' | 'AA' | 'AA-large''AA'Minimum WCAG contrast level
adjustmentStrategy'lightness' | 'saturation' | 'both''lightness'How color stops are adjusted
interpolationColorInterpolationCSS Color Level 4 interpolation
repeatingbooleanfalseUse repeating-linear-gradient