#CSS Variables

2 messages · Page 1 of 1 (latest)

soft walrusBOT
#

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

#

Yes, you can define and use CSS variables in Astro's frontmatter using the define:vars directive. This directive allows you to pass server-side variables from your component frontmatter into the client <script> or <style> tags.

Here's an example of how you can define and use CSS variables in Astro:

---const foregroundColor = "rgb(221 243 228)";
const backgroundColor = "rgb(24 121 78)";
---
<style define:vars={{ foregroundColor, backgroundColor }}> 
  h1 { 
    background-color: var(--backgroundColor); 
    color: var(--foregroundColor); 
  }
</style>
<h1>Hello</h1>

In this example, foregroundColor and backgroundColor are defined in the frontmatter and then used as CSS variables in the <style> tag.

However, please note that once these variables are defined and used, their values are not reactive and will not change. Astro components are templates that only run once, during the rendering step. If you need to change the value of these variables dynamically on the client side, you might need to use JavaScript in the browser to achieve that.

For more information, you can refer to the Astro documentation on CSS variables (https://docs.astro.build/en/guides/styling/#css-variables) and Astro Syntax (https://docs.astro.build/en/basics/astro-syntax#_top).

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