简体   繁体   中英

Why does css background-image not work?

I am trying to make a menu with a background-image but according to the web console, the browser can't find the image. I have this problem for a very long time and until now I don't know how to fix it. I think the solution is very simple but I don't find it.

The image is in the right map because if I load the image in a img tag the browsers shows the image.
I run it local host and I use Firefox

see my code below.

Can somebody help with solving this problem?

 body{ margin: 0px; } nav{ position: fixed; top:0px; width:100%; height:50px; background-image: url('img/menu1.jpg'); } 
 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="js/svg.js"></script> <link rel="stylesheet" type="text/css" href="css/index.css"/> </head> <body> <nav > <ul class="banner"> <li>Test menu</li> </ul> <ul class="menu"> </ul> </nav> </body> </html> 

Try to change your

background-image: url('img/menu1.jpg');

to

background-image: url('../img/menu1.jpg'); 

The path of your rule is relative to css file, not relative to html file.

Quote from Quick Reminder About File Paths

You have to pay attention to the relationship of where the file is that is referencing the image, and where that image actually is.

Here is all you need to know about relative file paths:

  • Starting with "/" returns to the root directory and starts there
  • Starting with "../" moves one directory backwards and starts there
  • Starting with "../../" moves two directories backwards and starts there (and so on...)

CSS文件中图像的URL应该相对于THAT文件,而不是HTML文档。

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