Using relative URL in CSS file, what location is i

2018-12-31 07:31发布

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

Suppose the file /stylesheets/base-styles.css contains:

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

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

标签: html css
8条回答
初与友歌
2楼-- · 2018-12-31 07:38

This worked for me. adding two dots and slash.

body{
    background: url(../images/yourimage.png);
}
查看更多
不再属于我。
3楼-- · 2018-12-31 07:40

It's relative to the stylesheet, but I'd recommend making the URLs relative to your URL:

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

That way, you can move your files around without needing to refactor them in the future.

查看更多
与风俱净
4楼-- · 2018-12-31 07:41

According to W3:

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

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

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.

查看更多
素衣白纱
6楼-- · 2018-12-31 07:50

Try using:

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

Images being folder holding the picture that you want to post.

查看更多
与风俱净
7楼-- · 2018-12-31 07:53

It's relative to the CSS file.

查看更多
登录 后发表回答