当在CSS文件中定义背景图像URL时,当使用相对URL时,它相对于哪里?例如:

假设文件/stylesheets/base-styles.css包含:

div#header { 
    background-image: url('images/header-background.jpg');
}

如果我将这个样式表通过<link…/> CSS文件中的相对URL是否相对于/stylesheets/中的样式表文档或相对于包含它的当前文档?可能的路径如下:

/item/details.html
/about/index.html
/about/extra/other.html
/index.html

当前回答

它相对于CSS文件。

其他回答

它相对于CSS文件。

尝试使用:

body {
  background-attachment: fixed;
  background-image: url(./Images/bg4.jpg);
}

图片是存放你想要发布的图片的文件夹。

对于CSS样式表,基本URI是样式表的URI,而不是源文档的URI。

(其他任何东西都会坏掉,IMNSHO)

根据W3:

部分url是相对于样式表的源进行解释的,而不是相对于文档

因此,在回答您的问题时,它将相对于/stylesheets/。

仔细想想,这是有道理的,因为CSS文件可以添加到不同目录下的页面中,因此将其标准化到CSS文件中意味着url可以在样式表链接的任何地方工作。

In order to create modular style sheets that are not dependent on the absolute location of a resource, authors may use relative URIs. Relative URIs (as defined in [RFC3986]) are resolved to full URIs using a base URI. RFC 3986, section 5, defines the normative algorithm for this process. For CSS style sheets, the base URI is that of the style sheet, not that of the source document. For example, suppose the following rule: body { background: url("yellow") } is located in a style sheet designated by the URI: http://www.example.org/style/basic.css The background of the source document's BODY will be tiled with whatever image is described by the resource designated by the URI http://www.example.org/style/yellow User agents may vary in how they handle invalid URIs or URIs that designate unavailable or inapplicable resources.

来自CSS 2.1规范。