CSS Files and Relative URLs
By coincidence, the day after I spoke about the confusion relative URLs can cause I was asked to help out on a project where relative URLs of a different kind were causing yet more confusion. This time it was URLs inside a CSS file.
Imagine your web page loads a CSS file like this:
<link rel="stylesheet" type="text/css" media="all" href="css/default.css" />
Note that the file is inside a "subfolder" of the database called "css". Inside this stylesheet we add a rule to place a background image in the header DIV like so:
div#header { background-image:url( images/header_background.gif ); }
Assuming the CSS file is located at /db.nsf/css/default.css you'd probably expect the image to load if it were located at /database.nsf/images/header_background.gif. But wait. It won't! Why? Because URLs inside CSS files are relative to the CSS file itself -- not the database and definitely not any BASE href in the web page, which has no effect on the relativeness of the URLs in the CSS files.
Come again!? Well, the stylesheet above lives inside a folder called "css". So, any URL it tries to load is relative to that folder. If you used a HTTP sniffer you'd see the browser try and load the background image from /db.nsf/css/images/header_background.gif.
The correct CSS is in fact:
div#header { background-image:url( ../images/header_background.gif ); }
The browser then knows to step back out of the CSS folder and then in to the images folder, both of which are at the same level in the database's faux-folder structure.
Similarly, if the stylesheet were two subfolders deep and in /db.nsf/css/screen/default.css then the rule would become:
div#header { background-image:url( ../../images/header_background.gif ); }
Again, this might seem like a noob thing, but it's another that can really trip people up until you learn how URLs inside CSS file behave.
This used to catch me out all the time, but since starting a new job and navigating file structures in linux (something I'd never previously done) its become completely obvious.
I never even gave this a second thought as it always seemed logical enough to me. But my original web work was on *ix based systems so everything for me has been relative to what was required there (command lines, scripting, etc.) and I've just never thought any differently about it...
Kind of narrow for me now that I think about it.
Ironically I just overcame the same "knuckle bleeding" experience myself.
I always think that after all these years of technology and the internet revolution.. billions of pages created, a simple, (dare I say a " notes-like") way, to do web development is still elusive and overly complicated.
It's like building with grains of sand, just one-grain falls out of place and it all comes down ...