2

I hava an absolute url in my stylesheet. http://localhost/images/myimage.jpg.

I also have a config class with the following constant

const SITE_ROOT = 'http://localhost/images'

On php pages i write config::SITE_ROOT . "/myimage.jpg" so when i move the site to the production server i can change the site root in one central location.

Is there any way to do this in my style sheet without putting it in the page? Relative url's are not an option because i am using mod rewrites and relative url's don't work.

2 Answers 2

8

You can write your SITE_ROOT constant into the CSS files by parsing them with PHP. Add this to .htaccess:

AddHandler application/x-httpd-php .css

Then embed PHP into the CSS files as you would do in any .php file.

3
  • 1
    This is a good way to do it. If you have multiple CSS files and only one or two require variables, then you can just use the file with the .php extention in your HTML link tag. It works equally well and won't load the server while returning regular CSS files. Nov 29, 2009 at 22:12
  • Thanks, i didn't realise that this was possible.Out of curiosity, why isn't this set to work by default when you rename css files with .php?
    – andrew
    Nov 29, 2009 at 22:22
  • andrew: not sure what you mean. If you rename any file to .php it should be parsed by default. This method allows you to keep the .css extension.
    – Ben James
    Nov 29, 2009 at 22:49
2

There is no way to do this with CSS. If you want to do something like this you could make it a PHP file and use variables that way.

But couldn't you just use absolute URLs?

background-image: url(/images/myimage.jpg);

Will work on any server, is not relative, and will find the files from the root.

2
  • Im almost certain that will not work on my site because i am using mod rewrites, plus i also wanted to know how to use constants in my css files, because it will certainly be useful
    – andrew
    Nov 29, 2009 at 22:16
  • I take it back, it does seem to work but the question was how can i use constants in my css files thanks
    – andrew
    Nov 29, 2009 at 22:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.