#How do you evaluate JS expressions within CSS style tags in a `.astro` file
1 messages · Page 1 of 1 (latest)
Hi @split moat. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro currently does not support direct templating within CSS inside <style> tags. This is due to the bracket syntax used in CSS and JavaScript being at odds with each other.
For example, if you try to do something like this:
---
const { zIndex } = Astro.props;
---
<style>
.navbar {
z-index: { zIndex };
}
</style>
Astro will not treat { zIndex } as an injected value, but rather as part of the CSS syntax.
A workaround for this issue is to build and inject a string. Here's an example:
---
const buildStyleString = (zIndex) => `
<style>
.navbar {
z-index: ${zIndex};
}
</style>
`;
---
{buildStyleString(10)}
In this example, buildStyleString is a JavaScript function that takes a zIndex value and returns a string containing the CSS rules with the zIndex value injected. This string is then inserted into the Astro component using curly braces {}.