How does CSS work in CakePhp?

To use cakephp’s framework to the fullest, you need to utilize its conventions. To modify the default template for your site copy:

/cake/libs/view/templates/layouts/default.thtml
 to /app/views/layouts/

You then edit that copied file. The presence of

/app/views/layouts/default.thtml

tells cake to stop looking at the old layout and look at the new one.

So you’d think that it would work the same way with css. Well almost. You don’t need to copy the css file, it’s already there for you in

/app/webroot/css/cake.generic.css

Ok great. Just delete that and copy your new css over the old stuff right? No, that’s not a great idea. If you do that you’ll lose all the cool cakephp css classes that you may want to take advantage of later on. For example ‘required’ and ‘optional’ classes for your form labels. Let’s keep the generic css and overwrite it’s classes as we need them.

How do we do that? Let’s go to the default.thtml and we’ll see:

$html->css('cake.generic');

That’s the same as putting

<link rel=“stylesheet” type=“text/css” 
href=“/ProjectPath/css/cake.generic.css” />

In your html code. Well that’s not exactly what we want to use because we want to use the @import url code to import our css files rather than link them.
Luckily the HtmlHelper::css function has an import option. So we use:
$html->css(’cake.custom’, import);

which yields :

@import url(ProjectPath/css/cake.custom.css);

between style tags.
Now that you have an idea of how the html helper css function works you can check out how to auto-load your css files for each controller.

Thanks,
Ian

Leave a Reply

You must be logged in to post a comment.