View Full Version : PHP and Paths in CSS

08-24-2007, 02:27 PM
Is there a way to set your path to image files in CSS dynamically with PHP.


Instead of this...

#menu a {
background: url("../images/button.jpg") 0 0 no-repeat;

I want to do something like this...

#menu a {
background: url("<?php echo $company['company_ttracker_path']; ?>images/button.jpg") 0 0 no-repeat;

08-24-2007, 02:31 PM
yes but for that to parse you would need to change from style.css to style.php and link to it normally.

08-24-2007, 03:00 PM
Also, don't forget that on your actual PHP page (that uses your CSS file),
you can also do an "inline CSS" style ... thus, you specifically change
one of the tags, example:

<div id="menu" style="background: url("<?=$company['company_ttracker_path'];?>") 0 0 no-repeat;">

The inline coding will take precedence over the one in the .css file.

08-24-2007, 03:08 PM
Thank you all for the help!!!

08-24-2007, 03:36 PM
You also need to change the MIME type if it's a PHP extension. Put header('Content-type: text/css') at the top (in PHP tags).

08-24-2007, 03:43 PM
Thanks for the help!

I am linking to the file like this from my main page...

<link rel="stylesheet" href="<?php echo $company['company_ttracker_path']; ?>css/main_ie7.php" type="text/css" media="all"/>

And I put this at the top of the code in main_ie7.php and renamed my file to main_ie7.php

header("Content-type: text/css")

The CSS works fine, but the paths are not working.

background-image: url("<?php echo $company['company_ttracker_path']; ?>images/dsg_portal_14.jpg");

Any thoughts?

Thanks again for any help!

08-24-2007, 03:49 PM
Maybe you're missing a slash?

background-image: url("<?php echo $company['company_ttracker_path']; ?>/images/dsg_portal_14.jpg");

08-24-2007, 03:50 PM
Thought that too, but I checked it and it is there...

08-24-2007, 03:51 PM
Is $company['company_ttracker_path']; being set in main_ie7.php?

08-24-2007, 05:04 PM
This sounds like trying to hammer a nail with a pair of scissors.

What I usually end up using when there is a dynamic path in my URL, is the <base> element. Both FireFox and IE are good at following this element, and it makes for a lot cleaner CSS and HTML.

Do a quick google on the <base> element, and try it out. This would prevent you from having to put PHP into every CSS/etc.

08-25-2007, 10:30 AM
Yeah I'd also check out the base tag, I use it on my own site and it's quite useful (that's why it's there for you to use).

08-25-2007, 01:00 PM
Gah - wrong thread