0
0
AstroHow-ToBeginner ยท 3 min read

How to Use define:vars in Astro Style for Scoped CSS Variables

In Astro, use define:vars inside a <style> tag to declare CSS variables scoped to the component. Write variables as a JavaScript object inside define:vars, then use them in your CSS with var(--variableName).
๐Ÿ“

Syntax

The define:vars directive lets you declare CSS variables inside an Astro component's <style> tag. You provide a JavaScript object where keys are variable names and values are their values. These variables become CSS custom properties scoped to the component.

  • define:vars={...}: JavaScript object with variable names and values.
  • Use var(--variableName) in CSS to access the variables.
astro
<style define:vars={ { primaryColor: '#4CAF50', paddingSize: '1rem' } }>
  .button {
    background-color: var(--primaryColor);
    padding: var(--paddingSize);
  }
</style>
๐Ÿ’ป

Example

This example shows how to define CSS variables using define:vars and use them in styles for a button. The variables primaryColor and paddingSize control the button's background color and padding.

astro
---
// No frontmatter needed for this example
---

<button class="button">Click me</button>

<style define:vars={ { primaryColor: '#007acc', paddingSize: '0.75rem' } }>
  .button {
    background-color: var(--primaryColor);
    padding: var(--paddingSize);
    border: none;
    color: white;
    border-radius: 4px;
    cursor: pointer;
  }
  .button:hover {
    background-color: #005fa3;
  }
</style>
Output
<button class="button" style="background-color: var(--primaryColor); padding: var(--paddingSize); border: none; color: white; border-radius: 4px; cursor: pointer;">Click me</button>
โš ๏ธ

Common Pitfalls

Common mistakes when using define:vars include:

  • Not using var(--variableName) syntax in CSS to access variables.
  • Defining variables outside the <style> tag or without define:vars attribute.
  • Using invalid JavaScript objects or missing quotes around string values.
  • Expecting variables to be global; they are scoped to the component only.
astro
<style>
  /* Wrong: No define:vars attribute, so variables won't be set */
  .box {
    color: var(--textColor);
  }
</style>

<style define:vars={ { textColor: 'red' } }>
  /* Right: define:vars used correctly */
  .box {
    color: var(--textColor);
  }
</style>
๐Ÿ“Š

Quick Reference

FeatureUsageNotes
Declare variables