#pass variable to style

5 messages · Page 1 of 1 (latest)

potent cove
#

I have these two number variables I import in my frontmatter:
import { svgMobileSize, svgDesktopSize } from '../../activityStore'

I use it like this:

<style define:vars={{ svgDesktopSize }}>
div {
display: flex;
gap: 1rem;
}

@media screen and (min-width: 768px) {
    div {
        flex-direction: column;
        align-items: center;
    }

    svg {
        width: var(--svgDesktopSize);
        height: var(--svgDesktopSize);
    }
}

</style>

But it doesn't change the size of my svgs

storm tigerBOT
#

Hi @potent cove. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Astro, when you use define:vars to pass a variable to a <style> tag, the variable is made available as a CSS custom property (CSS variable).

One common reason your SVG size might not be changing is that CSS variables require explicit units (like px, rem, or %) if the value being passed is a raw number. If svgDesktopSize is a number (e.g., 100), the browser will see width: 100;, which is invalid CSS.

You can fix this by appending the unit in your frontmatter or directly in the CSS using calc().

Option 1: Add units in the style tag

You can multiply the variable by 1px to ensure it is treated as a pixel value:

<style define:vars={{ svgDesktopSize }}>
  svg {
    /* Multiplied by 1px to turn a raw number into a pixel value */
    width: calc(var(--svgDesktopSize) * 1px);
    height: calc(var(--svgDesktopSize) * 1px);
  }
</style>

Option 2: Add units in the frontmatter

Alternatively, you can prepare the string in your component's frontmatter before passing it to define:vars:

---
import { svgDesktopSize } from '../../activityStore';
const desktopSizePx = `${svgDesktopSize}px`;
---

<style define:vars={{ desktopSizePx }}>
  svg {
    width: var(--desktopSizePx);
    height: var(--desktopSizePx);
  }
</style>

How define:vars works

The define:vars directive serializes your frontmatter variables using JSON.stringify() and injects them as CSS variables on the component's wrapper element [Template directives reference].

#

Any JSON-serializable variable is supported, including those imported into your frontmatter or passed via Astro.props [Template directives reference].

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@potent cove Kapa.ai is still learning and improving, please let me know how I did by reacting below.