如何在CSS文件的不同文件夹中使用相对文件路径?

时间:2021-07-22 19:35:54

I have a web page with the following folder structure:

我有一个具有以下文件夹结构的网页:

MyWebpage
  - css
    - layout.css
  - img
    - wallpaper.jpg
  - js
  - index.html

I have the following line included in index.html

我在index.html中包含以下行

<link rel="stylesheet" type="text/css" href="css/layout.css">

Now, I want to use the image wallpaper.jpg as the background for the <body> element. How can I use relative referencing here? Should I locate the file relative to the CSS file, like this,

现在,我想使用图像wallpaper.jpg作为元素的背景。我如何在这里使用相对引用?我应该找到相对于CSS文件的文件,像这样,

body {
  background: url('../img/wallpaper.jpg');
}

or relative to the HTML file, like this?

或相对于HTML文件,像这样?

body {
  background: url('img/wallpaper.jpg');
}

1 个解决方案

#1


2  

It really depends on where you are writing your CSS.

这实际上取决于你编写CSS的位置。

If you are writing an inline style or using <head> <style> tags in the HTML file, then use a path relative to the HTML file (../ in this case), as you are telling browser to load the image from the HTML file.

如果您正在编写内联样式或在HTML文件中使用

And if you are writing the style in the CSS file, the style is relative to the CSS file destination (no ../ in this case), as you will load the CSS file from the HTML file and the CSS file will load all the required resources.

如果你在CSS文件中编写样式,样式是相对于CSS文件目的地(在这种情况下没有../),因为你将从HTML文件加载CSS文件,CSS文件将加载所有所需资源。

#1


2  

It really depends on where you are writing your CSS.

这实际上取决于你编写CSS的位置。

If you are writing an inline style or using <head> <style> tags in the HTML file, then use a path relative to the HTML file (../ in this case), as you are telling browser to load the image from the HTML file.

如果您正在编写内联样式或在HTML文件中使用

And if you are writing the style in the CSS file, the style is relative to the CSS file destination (no ../ in this case), as you will load the CSS file from the HTML file and the CSS file will load all the required resources.

如果你在CSS文件中编写样式,样式是相对于CSS文件目的地(在这种情况下没有../),因为你将从HTML文件加载CSS文件,CSS文件将加载所有所需资源。