I'm using sveltekit and I'm wondering how to import an image and use it in a CSS background property.
Here's what I've tried:
<script>
import img from '$lib/images/background-shaded.jpg';
</script>
<div>
<h1>Hello World</h1>
</div>
<style>
div {
background-image: url({img});
}
</style>
For now, I'm just putting the image in the the static folder and using via it's URL. Maybe that's the recommended approach...
Thanks.
You don't have to import the image at all. Vite will resolve URLs in CSS:
div {
background-image: url("$lib/images/background-shaded.jpg");
}
(On build an asset will be emitted and the URL is replaced accordingly.)