Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use asset URLs in style binding with Vite

I want to show a background image from my assets folder. When I use an image tag, the image is shown properly, so the image is well placed, but throws a 404 when I use the background-image style. Any idea about what is happening?. I am using Vue 3 with TypeScript and Vite 2.

This does not resolve the URL:

<div style="background-image: url(./assets/img/header.png)"
></div>

But this does:

<img src="./assets/img/header.png" alt="Header" />
like image 868
Francisco Martin Avatar asked Dec 03 '25 00:12

Francisco Martin


1 Answers

The URL needs to be resolved with import in <script>. @vue/compiler-sfc does not automatically resolve the URLs in <div>.style, but it does for <img>.src, which is why your second example works correctly.

Solution

Use the import keyword in a <script> block to expose the resolved image URL to the template:

<script setup>
import imagePath from '@/assets/logo.svg'
</script>

<template>
  <div class="logo" :style="{ backgroundImage: `url(${imagePath})` }"></div>
</template>

<style>
.logo {
  height: 400px;
  width: 400px;
}
</style>

demo

like image 59
tony19 Avatar answered Dec 05 '25 15:12

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!