javascriptbackgroundastrojs

Astro pass varaiable for background image


I want to pass an image url to a local style.

---
let backgroundUrl = '../assets/images/header-startseite.webp'
---

<Header backgroundUrl={backgroundUrl}/>

in the Header component:

export interface Props {

    backgroundUrl: string
}

const {backgroundUrl} = Astro.props

<style define:vars={{ backgroundUrl }}>
  .header {
    background-image: url('var(--backgroundUrl)');
  }
</style>

But that is not working..I use Astro 3.5 Help would be great. Thanks


Solution

  • As of today, you can also use the API:

    ---
    import BgImage from 'assets/bg-image.jpg'
    import { getImage } from 'astro:assets'
    
    const bgImage = await getImage({ src: BgImage })
    ---
    
    <div style={`background-image: url(${bgImage.src});`}></div>
    

    Alternatively, apply a class and use a CSS style block with define:vars as shown in Alex's answer.