Drupal 6 Theming Cookbook
上QQ阅读APP看书,第一时间看更新

Including a CSS file in a theme

This recipe details the steps involved in adding a CSS file to the theme via its .info file. In this case, we will be adding a CSS file to the mytheme sub-theme which we created earlier in this chapter.

Getting ready

Create a CSS file inside the theme's folder named mytheme.css and add the following example rule to it:

* {
color: #996633 !important;
}

This rule should override and change the color of all text on the page to a brownish hue.

How to do it...

Adding a CSS file to a theme is best accomplished via its .info file. Navigate to the theme's folder at sites/all/themes/mytheme and open the mytheme.info file in an editor. Add the following line to this file to include our CSS:

stylesheets[all][] = mytheme.css

Tip

If the CSS file is stored along with other stylesheets in a sub-folder named css, the syntax would include the relative path to the file as follows: stylesheets[all][] = css/mytheme.css.

Once done, save the file and exit the editor. Since we have modified the .info file and introduced a new file, our changes will not take effect until the theme registry is rebuilt. Therefore, clear the Drupal cache and view the site to confirm that our new stylesheet has been included correctly. The theme should now display all text in brown.

How it works...

Drupal checks the .info file and notes that we have declared stylesheets using the stylesheets variable. The syntax of this variable is similar to that of an array in PHP. The all index in the syntax represents the media type as used in CSS declarations.

The next screenshot displays a section of the source code of a page which confirms the inclusion of the new stylesheet, mytheme.css. We can also see that our sub-theme is including the stylesheets declared by its base theme—Garland—as well as its own stylesheets.

How it works...

Note

In the preceding screenshot, we can see that Drupal references each stylesheet along with a query string. For example, mytheme.css is included as mytheme.css?e. This rather quirky suffix is a trick used by Drupal to ensure that browsers do not use stale copies of a cached CSS file while rendering our site.

We can test this by clearing the Drupal cache and viewing the source code once again. Now, our stylesheets should have a different suffix—perhaps, something like mytheme.css?A—thereby tricking browsers into believing that these are different files and using them instead of their cached copies.

There's more...

One of the advantages of using a sub-theme is that we can easily override elements of the base theme. This includes stylesheets as well.

Overriding the base theme's stylesheet

If the base theme includes a stylesheet named layout.css, adding a stylesheet of the same name in the sub-theme will override the base theme's stylesheet. In other words, Drupal will include the sub-theme's stylesheet instead of that of the base theme.