为什么url()函数的绝对路径不起作用?

时间:2019-10-20 18:47:49

标签: css

我正在尝试通过CSS在网站的背景上显示图片。我希望将图像保存在与CSS / HTML文件不同的文件夹中。如果将图像与CSS / HTML文件放在同一文件夹中,并且仅引用其名称,则仅显示该图像。

代码位于C:\Users\User\Desktop\project\templates中,图像位于C:\Users\User\Desktop\project\pictures中。如果我尝试使用绝对路径,它将不会显示。仅当我将图片放在模板文件夹中时才会显示。

<!--This code works if I place the picture in the template file-->

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("picture.png");
}
</style>
</head>
</html>

<!--This code doesn't work-->

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("C:\Users\User\Desktop\project\pictures\picture.png");
}
</style>
</head>
</html>

2 个答案:

答案 0 :(得分:0)

使用此CSS

Body{

background-image: url("../pictures/picture.png")
}

答案 1 :(得分:0)

根据您的文件夹结构,您可能需要执行 ../ pictures / picture.png

background-image: url("../pcitures/picture.png");

在图片文件夹中查找图片。第一个'。'表示当前目录(.css文件),第二个'../'表示父目录(项目文件夹)。从那里,您导航到图片文件夹,然后直接与图片图像链接。使用此链接来了解文件路径。 https://en.wikipedia.org/wiki/Path_(computing)

避免使用绝对文件路径。想象一下,将文件传输到新服务器上,您将不得不再次重写文件路径。

 background-image: url("C:\Users\User\Desktop\project\pictures\picture.png");
相关问题