简体   繁体   中英

Cant load image with html. only works in css

I have my css which contains a class

.Img{
  background: url('../assets/Trump.png');
}

And the html looks like this :

<div class="Img">

But when I want to have it like this

<div class="Img" style="background: url('../assets/Trump.png');">

the image won't load for me and I get an error

>GET http://localhost:8080/assets/Trump.png 404 (Not Found)

I am working with vue.js 2.0 and webpack

The main issue here is relative paths.

If you have this structure for example:

/page.html
/static/
       /assets/
              /Trump.png
       /css/
           /file.css

And inside your page.html you have a <link> tag to your css (in static/assets/css/file.css ), the call to ../assets/Trump.png from that css file will get to the correct place (because from the /css directory - 1 directory up is the static directory, and from there we go inside the assets and everything is ok).

However - If we are inside the / directory (where the page.html exists), this is also our root directory, when we try to go to ../assets/Trump.png the relative path we get is /assets/Trump.png (which does not exists in our server. The correct path should be /static/assets/Trump.png ).

You should check the structure of your directories and put the correct relative path.

删除url()的撇号, url()函数不需要它们

<div class="Img" style="background: url(../assets/Trump.png);">

Edit your image url to this

<div class="Img" style="background-image: url('assets/Trump.png');">

when you are declaring this background-property in your css the url is correct the assets folder is in the parent directory of css. but when using inline css the assets and the html file are in the same directory that is why you are getting this error.

Check your image path, there's a chance that's the issue. Check this out: CSS background image URL path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM