Need some help with your project? Contact me

I’m Hooked! 7: Using hook_css_alter()

This week we will look at hook_css_alter(), a hook designed to act on .css files before they are being included on the page. Using this hook you can easily stop a .css file or group of files from being added to the page.

To illustrate the use of this hook, I’m going to show you how to stop a .css file from getting added to a page. Let’s say we are uncomfortable with the node.css file provided by the Node module, and we want to remove it as our module replaces it with something else.

In a previous post in this series, we saw a way this could be achieved. However, if this is the only thing you need to do, i.e. stop a .css file from getting added to the page, this is the hook for you. So this is the code to getting this done:

function demo_css_alter(&$css) {
  $path = drupal_get_path('module', 'node') . '/node.css';

As you can see in the code above, the demo module implements hook_css_alter() and makes use of the $css parameter that gets passed to the function by reference. This array contains reference to all the .css files provided by modules and themes that are about to be added to the page. Each key represents the relative path to the actual file.

The $path variable you see above stores the path to the node.css file found in the Node module folder and is used in the unset() function to identify which array element we want to unset. And that’s pretty much it. Now it’s your task to play around and see what else you can do with this hook. Like usual, krumo the parameter out (in this case $css) and see what’s in there to play around with.

Hope this helps.


Nice code on hook css alter(). it really helped me.... thanks :)

if some css files are removed in a parent theme's hook_css_alter is it possible to add them back in sub theme?

Add new comment

You can post comments in Markdown and basic HTML tags.
For code blocks, wrap your code within '~~~'. For example:
$var = 'my variable';