Local background image not displaying in html

与世无争的帅哥 提交于 2021-02-05 11:18:52

问题


I am trying to get background images working for html output from a system I develop for. I can output the page correctly, but the background images do not correctly display when referencing a file on the local machine; however if I reference the same image from an external site it works correctly.

I have the html file saved at <USER_DOCUMENTS>\Test_HTML.html and the example local image saved at <USER_DOCUMENTS>\images\test_image.png. The image I am using for the example is this, but any suitable image that can be externally referenced should suffice.

Test_HTML.html

<html>
   <head>
      <style>
         td{font-family:arial; font-size:12pt; border:solid black 1pt;}
         .test_class{background-image:url(images\test_image.png); background-repeat:repeat; background-position:top left;}
      </style>
   </head>
   <table>
      <tr>
         <td class="test_class" style="width:40pt">Baap</td>
         <td class="test_class" style="width:60pt">Beep</td>
         <td class="test_class" style="width:80pt">Biip</td>
         <td class="test_class" style="width:100pt">Boop</td>
         <td class="test_class" style="width:120pt">Buup</td>
      </tr>
   </table>
   <hr/>
   <img src="images\test_image.png"/>
</html>

When viewing this in a browser (tested in Chrome, Firefox & IE), the image below the horizontal rule displays correctly, but there is no background displayed in the table. However if url(images\test_image.png) is replaced with url(<EXTERNAL_FILE_LOCATION>) then the background images display correctly. The desired behaviour is to be able to use the local file and get the same output as when using an external file location.

I'm at a bit of a loss as to how to get this to work correctly on the local system, and any help would be appreciated.


回答1:


Like, I mentioned in my comment above, "\" or backslash is generally used for referring to the absolute path of a path and is a Windows standard for referring to the location of files. We make use of "/" or forward slashes as they are used to refer to the relative path with the current working file. So,

./ refers to the current working directory.

../ refers to the parent directory.

./images/ refers to a folder which is present in the same location as the working directory and likewise to access the files inside the folder, you put a forward slash to refer to it.

As for, why it worked when you used the backslash path inside the img tag but not in the css, I'm not really sure of. But it's not a good practice and definitely not the proper way of doing things. Hope, it helps.




回答2:


Replace the slash '\' to '/'. URL's have to be in forward slash



来源:https://stackoverflow.com/questions/47454170/local-background-image-not-displaying-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!