J Bryan Price
J Bryan Price

Reputation: 1384

Relative paths in redirected CSS file

I'm aware of the fact that relative paths in CSS are supposed to be based on the location of the CSS file, as answered by Using relative URL in CSS file, what location is it relative to? and Is a relative path in a CSS file relative to the CSS file?.

However, I have a content management site in which I allow overriding CSS when needed. I generate links in head for all the sections of a page, with a format like:

<link rel="stylesheet" type="text/css" href="/content/data/?s=123&get=.css">

If the section displayed is to use a default, static CSS file, that fact is detected by the page that serves /content/data/; in this case, it serves a redirect to that static file.

These static CSS files may contain relative paths to images stored in nearby folders, so when my CSS file is at /some-folder/styles/file.css and it contains

body { background-image: url(../images/section-123-bg.png); }

the browser looks for /some-folder/images/section-123-bg.png.

This does not seem to be an issue in Chrome, Safari or Firefox. IE, however, seems to look for /content/images/section-123-bg.png. It appears to treat /content/data/ as the base path of the CSS file it ends up with.

My question is:

Which source path is a browser supposed to start from when calculating relative paths in a CSS file?

Upvotes: 4

Views: 1542

Answers (1)

Danny Tuppeny
Danny Tuppeny

Reputation: 42333

I had a similar issue - we're having to proxy CSS files for a legacy app, and all the relative paths are being resolved from the proxy script, not the real locations.

The easiest fix was for us to change the proxy script to output a fake CSS file that @imports the other CSS file instead.

public ActionResult Bundle(string type, string bundle)
{
    var url = Scripts.Url(bundle).ToString();
    var cssContent = string.Format("@import url('{0}');", url.Replace("'", @"\'"));

    return Content(cssContent, "text/css");
}

Upvotes: 1

Related Questions