最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Astro pass varaiable for background image - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

Normally 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:

  1. 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>
  1. 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.

发布评论

评论列表(0)

  1. 暂无评论