I want to pass an image url to a local style.
---
let backgroundUrl = '../assets/images/header-startseite.webp'
---
<Header backgroundUrl={backgroundUrl}/>
in the Header ponent:
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
I want to pass an image url to a local style.
---
let backgroundUrl = '../assets/images/header-startseite.webp'
---
<Header backgroundUrl={backgroundUrl}/>
in the Header ponent:
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
Share Improve this question edited Mar 7, 2024 at 16:18 VLAZ 29.1k9 gold badges63 silver badges84 bronze badges asked Nov 13, 2023 at 17:02 WernerWerner 3393 silver badges13 bronze badges2 Answers
Reset to default 5Normally you would need to put url into the variable e.g.:
let backgroundUrl = 'url(../assets/images/header-startseite.webp)'
...
background-image: var(--backgroundUrl);
But it seems this won't work for images in src
or assets
by default.
A few ways I think:
- Import the image and use
src
in the CSS variable.
---
import backgroundUrl from "../assets/images/header-startseite.webp";
---
<Header backgroundUrl={`url(${backgroundUrl.src})`} />
Header ponent:
<style define:vars={{ backgroundUrl }}>
.header {
background-image: var(--backgroundUrl);
}
</style>
- Move these background images to the
public
folder and reference them that way:
let backgroundUrl = 'url(/images/header-startseite.webp)' // public/images/*
// Header ponent like above
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.