Can you specify a file path in the CSS file relative to the HTML file?

63 Views Asked by At

A relative path in a CSS file is relative to that CSS file. Is there any way to change that default behavior though? My use case for this would be to give web pages individual backgrounds. It would be nice to have

body { background-image: url("banner.jpg"); }

once in the CSS file and just let the browser know to look for banner.jpg in the same directly as the HTML (first?), rather than have

<style> body { background-image: url("banner.jpg"); } </style>

in the head of every single HTML file. The ideal here would be to mimic the behavior of the PATH shell variable, specifying multiple paths in order of precedence, to tell the browser "look in the same directly as the HTML file first for a banner.jpg, but if it's not there go use the default one in the same directory as the CSS file."

1

There are 1 best solutions below

0
Quentin On

Is there any way to change that default behavior though?

No.

Your options are:

  • The custom stylesheet on a per-page basis you have already mentioned
  • Writing unique selectors for the body elements on different pages (e.g. by adding class attributes).
  • Dynamically generating the rule at runtime using JavaScript, the location object, and a lookup table.