Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set background image url for local files?

Tags:

html

vue.js

I want to paste a relative image url to a div to set it as the background image. Unfortunately the div won't render the image. So this works fine and renders the image

<img src="../assets/images/HeroImg.jpg">

but this one doesn't

<div style="background-image: url(../assets/images/HeroImg.jpg)">
    Content goes here
</div>

Things I also tried:

  • wrapping the url inside single quotes
  • assets/images/HeroImg.jpg maybe?
  • ./assets/images/HeroImg.jpg starting from the src folder
  • images/HeroImg.jpg and ./images/HeroImg.jpg starting from the assets folder

What is the correct url to use for background images?


Update

I'm using VueJs so things might be different here? Steps to reproduce:

  • Create a new project using the Vue CLI
  • Create a images directory in src/assets
  • Create an image in src/assets/images and call it HeroImg
  • Update App.vue file with

.

<template>
  <div id="app">
    <div>
      This works:
    </div>
    <div>
      <img src="./assets/images/HeroImg.jpg">
    </div>
    <div>
      This doesn't work:
    </div>
    <div style="background-image: url('./assets/images/HeroImg.jpg')">
        Content without background image
    </div>
  </div>
</template>

You will see that the img tag renders the image but not the div with the background image.

like image 620
Question3r Avatar asked Nov 26 '25 05:11

Question3r


1 Answers

Terry's answer did the trick but I needed an extra set of parentheses around the url tag content:

computed: {
  heroImage() {
    return {
      backgroundImage: `url(${require('../assets/images/HeroImg.jpg')})`
    };
  }
}
like image 197
Stephen Avatar answered Nov 27 '25 22:11

Stephen



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!