withastro / astro

The web framework for content-driven websites. ⭐️ Star to support our work!
https://astro.build
Other
46.78k stars 2.48k forks source link

style define:vars not working on child component #11156

Closed aleandro-coppola closed 5 months ago

aleandro-coppola commented 5 months ago

Astro Info

Astro                    v4.9.1
Node                     v21.5.0
System                   macOS (x64)
Package Manager          npm
Output                   static
Adapter                  none
Integrations             @astrojs/tailwind
                         @storyblok/astro
                         astro-icon
                         @astrojs/react

If this issue only occurs in one browser, which browser is a problem?

Chrome

Describe the Bug

On DefaultLayout.astro


---
import '@assets/css/global.css';
import '@assets/css/utilities.css';
import '@assets/css/elements/elements.css';
import '@assets/css/components/components.css';
import '@assets/css/animations/animations.css';

import AppSiteConfig from 'src/core/components/AppSiteConfig.astro';
---

<html lang='it' dir='ltr'>
  <head> </head>
  <body class='relative'>
    <AppSiteConfig />
  </body>
</html>

I add a child component AppSiteconfig.astro with this code

---
const colorPrimary = '255 103 40';
---

<h1 style={{ color: `rgb(var(--color-primary))` }}>Test2</h1>

<style define:vars={{ colorPrimary }}>
  :root {
    --color-primary: var(--colorPrimary);
  }
</style>

But the --color-primary not working The same code directly on DefaultLayout.astro works:


---
import '@assets/css/global.css';
import '@assets/css/utilities.css';
import '@assets/css/elements/elements.css';
import '@assets/css/components/components.css';
import '@assets/css/animations/animations.css';

import AppSiteConfig from 'src/core/components/AppSiteConfig.astro';

const colorPrimary = '255 103 40';
---

<html lang='it' dir='ltr'>
  <head> </head>
  <body class='relative'>
    <h1 style={{ color: `rgb(var(--color-primary))` }}>Test2</h1>

    <style define:vars={{ colorPrimary }}>
      :root {
        --color-primary: var(--colorPrimary);
      }
    </style>
  </body>
</html>

What's the expected result?

Screenshot 2024-05-27 alle 15 10 15

Link to Minimal Reproducible Example

https://stackblitz.com/edit/astro-hvhglr

Participation

matthewp commented 5 months ago

This is a limitation of how define:vars works. It cannot define variables in parent components. This is because the way it works is to attach the values to the elements within the template. So although your selector is at the root, the actual value of the variables is in the h1 in that template, thus it never selects. If you change the selector to h1 it works.