Yii: CSS file order with registerCssFile

In Yii there are different ways to include stylesheet. It can be done by inserting HTML code into header page, as shown in default layout files (eg yii/protected/views/layouts/main.php). it can also be done by calling registerCssFile().

I’ve been using the HTML code method because that’s the default when setting up an Yii project.

Recently I wanted to develop a new theme using Foundation Framework. I used the Foundation 3 extension which does the hardwork and cuts down development time.

However I ran into problem with presentation of the site when some pages has its own stylesheet with this extension.

The intended order of stylesheet should be Foundation, theme and page. However it becomes Foundation, page, theme. Certain classes defined for the page becomes reset or overwritten by the theme specific stylesheet.

This is not a problem with extension but with how the files are included to the page with registerCssFile(). The method doesn’t have option to specify the order. The foundation stylesheet and page specific stylesheet were included with this method, yet the theme specific stylesheet was included as html code in the main theme layout. Even if the theme specific stylesheet was included with the method, the order was still wrong.

To ensure the page specific stylesheets comes after the default theme stylesheet, call registerCssFile() method in the controller.

ie, in <path to project>/yii/protected/components/Controller.php, edit function init():

public function init() {
    parent::init();
    Yii::app()->clientScript->registerCssFile(Yii::app()->request->baseUrl .'/css/main.css');
    // if you use theme, this includes theme specific stylesheet
    Yii::app()->clientScript->registerCssFile(Yii::app()->theme->baseUrl .'/css/main.css');
}

The stylesheet orders now looks correct.

I came up with this solution while researching about the problem and ended up in this forum post. Yii experts, let me know if this is not the correct way to do it.

1 thought on “Yii: CSS file order with registerCssFile

Leave a Reply

Your email address will not be published. Required fields are marked *