#background-image with getImage

4 messages · Page 1 of 1 (latest)

slate spindle
#

import { getImage } from 'astro:assets'
import background from '../images/pexels-thirdman-8942612.jpg'

const optimizedBackground = await getImage({ src: background, format: 'avif' })

<div id='wrapper'></div>

<style define:vars={{ backgroundSrc: optimizedBackground.src }}>
#wrapper {
height: 100dvh;
background-image: var(--backgroundSrc);
background-size: cover;
background-position: center;
}
</style>

The background doesn't seem to load with this code. It will work with the following code:

import { getImage } from 'astro:assets'
import background from '../images/pexels-thirdman-8942612.jpg'

const optimizedBackground = await getImage({ src: background, format: 'avif' })

<div style={background-image: url(${optimizedBackground.src});} id='wrapper'>
</div>

<style define:vars={{ backgroundSrc: optimizedBackground.src }}>
#wrapper {
height: 100dvh;
background-size: cover;
background-position: center;
}
</style>

Why doesn't the first set of code work?

spark knotBOT
#

Hi @slate spindle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The issue is not Astro-specific — it's a CSS behavior. When you use var(--backgroundSrc) as the value of background-image, CSS receives just the raw URL string (e.g. /_astro/image.hash.avif), but background-image requires it to be wrapped in url(). A bare string is not a valid value for background-image.

So this doesn't work:

background-image: var(--backgroundSrc); /* resolves to just the path string */

But this does work:

background-image: url(/_astro/image.hash.avif); /* valid CSS */

The second code snippet works because you're setting the background-image inline with the url() wrapper already included:

<div style={`background-image: url(${optimizedBackground.src});`} id='wrapper'>

The fix — if you want to keep using CSS custom properties, wrap the variable in url() in your stylesheet:

---
import { getImage } from 'astro:assets'
import background from '../images/pexels-thirdman-8942612.jpg'

const optimizedBackground = await getImage({ src: background, format: 'avif' })
---

<div id='wrapper'></div>

<style define:vars={{ backgroundSrc: optimizedBackground.src }}>
    #wrapper {
        height: 100dvh;
        background-image: url(var(--backgroundSrc));
        background-size: cover;
        background-position: center;
    }
</style>

Note: url(var(--backgroundSrc)) has limited browser support. The most reliable approach remains the inline style method you already found working. [getImage() reference]

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@slate spindle Kapa.ai is still learning and improving, please let me know how I did by reacting below.