当在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样式表,基本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规范。


它相对于样式表,但我建议让URL相对于你的URL:

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

这样,您就可以移动您的文件,而不需要在将来重构它们。


当使用css的自动最小化时,可能会出现一个问题,似乎打破了这一点。缩小包的请求路径可以与原始css的路径不同。这可能会自动发生,所以会引起混乱。

迷你包的映射请求路径应该是“/originalcssfolder/minifiedbundlename”而不是“minifiedbundlename”。

换句话说,将你的包命名为与原始文件夹结构相同的路径(带有/),这样任何外部资源,如字体,图像将被浏览器映射到正确的uri。另一种方法是在css中使用绝对url(refs),但这通常不是可取的。


尝试使用:

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

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