Profile picture for user admin
Daniel Sipos
20 Mar 2013

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';
  unset($css[$path]);
}

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.

Profile picture for user admin

Daniel Sipos

CEO @ Web Omelette

Danny founded WEBOMELETTE in 2012 as a passion project, mostly writing about Drupal problems he faced day to day, as well as about new technologies and things that he thought other developers would find useful. Now he now manages a team of developers and designers, delivering quality products that make businesses successful.

Contact us

Comments

David Jony 14 Jul 2014 18:31

Hook Css Alter

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

sepehr 28 Jul 2014 11:33

if some css files are removed

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