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 withoutdefine:varsattribute. - 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
| Feature | Usage | Notes |
|---|---|---|
| Declare variables | Variables scoped to component | |
| Use variables | var(--varName) | Use inside CSS rules |
| Variable types | Strings, colors, sizes | Any valid CSS value |
| Scope | Component only | Not global across app |
| Common error | Missing define:vars attribute | Variables won't apply |
Key Takeaways
Use
define:vars inside <style> to declare scoped CSS variables in Astro.Access variables in CSS with
var(--variableName) syntax.Variables are scoped to the component and not global.
Always provide a valid JavaScript object to
define:vars with string values.Forget to add
define:vars attribute means variables won't be set.