background-image: url() 当所有文件都在桌面上但文件夹中没有文件时有效

background-image: url() works when all files on desktop but not with files in their folders

当使用背景图像 url() 设置完整的封面背景图像时,我遇到了一个我无法弄清楚的问题。当我的桌面上有 index.html 文件、main.css 文件和图像文件时,图像在浏览器中显示正常。但是,当我将 .jpg 移动到 imgs 文件夹并将 .css 文件 enter image description here 移动到 css 文件夹时,图像不会出现在浏览器中。

代码完全是从W3复制过来的,所以我想一定是我的文件夹结构有问题,但是我看不到。我以前从未见过这个问题。提前致谢!

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>My Site</title>
    <link rel="stylesheet" type="text/css" href="css/main.css" />
  </head>

  <body>
    <div class="bg"></div>
  </body>
</html>


body,
html {
  height: 100%;
}

.bg {
  background-image: url("/imgs/ocean.jpg");
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

在高度和宽度中使用像素并检查背景图像的路径

.bg {
  background-image: url("imgs/ocean.jpg");
  width:100%;
  height: 100px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

在路径的开头使用 / 将使用根目录,在本例中为 C:

改用这个:

background-image: url("../imgs/ocean.jpg");

尝试使用

background-image: url("../imgs/ocean.jpg");

改用此语法:因为 ./ 指的是当前文件夹,../ 指的是父目录,应该使用那个。

background-image: url("../imgs/ocean.jpg");

虽然这里的其他答案是正确的,但他们在解释 'why' 方面做得不是很好。

background-image: url("../imgs/ocean.jpg"); 应该适合你。

原因如下:

在目录路径中,路径开头的两个点 ../ 表示相对于当前工作目录上升一个级别(即,如果在您的 index.html 文件中使用,搜索将开始从那里)。您可以上多级,即 ../../../ 上三级。路径开头的单个点 ./ 表示沿着路径,从 这里 开始。 路径开头的单斜杠 / 将使用根目录,在 Windows 上通常是您的 C: 驱动器,或者在 Linux/Unix/Mac 上是文件的最开始树.

在 main.css 文件中使用了以下代码,它正在运行:

body,
html {
  height: 100%;
}

.bg {
  **background-image:** url("../imgs/ocean.jpg");
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}