ImageToSVG

How to Use CSS Variables in SVG

CSS custom properties work inside inline SVG — use them to theme SVG icons, switch dark/light mode, and control SVG colors from a single CSS variable.

Preset:
Colors:
VTracer vectorization + SVGO optimizationPrivacy protected

CSS Variables in Inline SVG

CSS variables defined in :root cascade into inline SVG elements — use them for SVG fill and stroke colors.

  • :root { --brand-primary: #3b82f6; }
  • In SVG: <path fill='var(--brand-primary)' />
  • Changing --brand-primary in CSS changes all SVG paths using it instantly
  • Works for fill, stroke, stop-color in gradients, and filter values
  • Dark mode: @media (prefers-color-scheme: dark) { :root { --brand-primary: #93c5fd; } }

CSS Variables in External SVG Files

External SVG files (loaded via <img> or CSS background) cannot access CSS variables from the HTML document.

  • <img src='icon.svg'>: isolated — no CSS variable inheritance
  • CSS background-image: url('icon.svg'): isolated — no CSS variable inheritance
  • Solution 1: Use inline SVG (paste SVG code directly in HTML)
  • Solution 2: Use SVG as <object> or <iframe> — partial variable inheritance
  • Solution 3: Dynamically load SVG text and inline it with JavaScript

Frequently Asked Questions

Can I use CSS variables in an SVG file loaded with <img>?

No — SVG files loaded as images are isolated from the document's CSS. CSS variables from the parent HTML document don't cascade into them. Use inline SVG or load the SVG with JavaScript and insert it inline.

How do I theme multiple SVG icons with one CSS variable?

Use inline SVG for each icon with fill='var(--icon-color)'. Set --icon-color on :root or on a parent container. All icons inherit the variable. Change --icon-color and all icons update — perfect for dark/light mode.

Do CSS variables work in SVG gradients?

Yes — use currentColor or var(--color) in <stop stop-color> attributes. Example: <stop stop-color='var(--gradient-start)' />. Changing the variable dynamically updates the gradient.

Can React or Next.js SVG components use CSS variables?

Yes — React/Next.js inline SVG components are part of the DOM and inherit CSS variables from parent components or :root. Use fill={`var(--icon-color)`} in JSX SVG attributes. Tailwind v4 CSS-first tokens are CSS variables — they work natively in inline SVG.

Related guides

Ready to Convert Your Image to SVG?

Free online converter — no sign-up, no watermarks, results in under 3 seconds.

Try It Free — Convert Image to SVG