在 CSS 文件中使用相对 URL,它相对于什么位置? [英] Using relative URL in CSS file, what location is it relative to?

查看:22
本文介绍了在 CSS 文件中使用相对 URL,它相对于什么位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When defining something like a background image URL in a CSS file, when using a relative URL, where is it relative to? For example:

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

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

如果我通过 <link .../> 将此样式表包含到不同的文档中,CSS 文件中的相对 URL 是否会相对于样式表文档/stylesheets/相对于当前文档 包含它?可能的路径,例如:

If I include this style-sheet into different documents via <link ... /> will the relative URL in the CSS file be relative to the stylesheet document in /stylesheets/ or relative to the current document it's included to? Possible paths like:

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

推荐答案

根据W3:

部分 URL 被解释为相对于样式表的来源,而不是相对于文档

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document

因此,在回答您的问题时,它将与 /stylesheets/ 相关.

Therefore, in answer to your question, it will be relative to /stylesheets/.

如果您考虑这一点,这是有道理的,因为 CSS 文件可以添加到不同目录中的页面中,因此将其标准化为 CSS 文件意味着 URL 将在样式表链接的任何位置起作用.

If you think about this, this makes sense, since the CSS file could be added to pages in different directories, so standardising it to the CSS file means that the URLs will work wherever the stylesheets are linked.

这篇关于在 CSS 文件中使用相对 URL,它相对于什么位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆