Search code examples
cssurlcakephpimagestylesheet

How are URLs handled inside the CSS file in CakePHP so they reference the correct location?


I am designing a website using CSS Files a lot, but I have several occurrences of background images, images for bullets in lists and I will probably find another need for the css url() function.

But, in cake, all URL should be handled by the Route::url() function, in several ways, being most common the $html->url()

But my problem is that CSS Files are not interpreted by PHP. How I can create a CSS File containing something like:

div.coolbg {
  background-image: url('<?= $html->url("/img/coolbg.jpg") ?>');
}

See, my last option is to import the css file inline on the layout so it can be interpreted. But I highly prefer to use a more "Cake" approach.

Thanks!


Solution

  • You don't need to use $html->url() in your css file, consequently you don't need to parse the CSS files through PHP or create a CssController.

    If your cake app is installed in your virtual hosts DocumentRoot, just make all the paths to images absolute from the webroot. e.g.

    div.coolbg {
      background-image: url(/img/coolbg.jpg);
    }
    

    This will apply the image at app/webroot/img/coolbg.jpg to your

    If your cake app is not installed in the virtual hosts DocumentRoot, i.e. you access your cake app via a URL like http://www.domain.com/myapp/, then you make the path to the image relative to the css file. Check out the style rules in app/webroot/css/cake.generic.css e.g.

    #header h1 {
    background:#003D4C url(../img/cake.icon.gif) no-repeat scroll left center;
    color:#FFFFFF;
    padding:0 30px;
    }
    

    This works because style sheets live in the app/webroot/css/ directory, and image live in the app/webroot/img/ directory, so the path "../img/cake.icon.gif" comes up out of the css directory, then back down into the img directory.