Adding Stylesheets to a Drupal Module

Written by James Mansson on January 25, 2013 Categories: CSS, Drupal

Although I have found Drupal to be a powerful means of creating content-driven websites, it can be frustrating in that the way to do certain things is neither obvious nor well-documented. This, I think, a consequence of the desired to hide the details of the implementation, and to allow users to concentrate on creating site content. While this is certainly desirable for routine tasks, there are occasions when you need to control things at a lower level, and in those circumstances, it can be hard to see how you do what you want to do.

Recently, I needed to change the styling of a block on a Drupal website I manage. This block contained the Twitter feed for the organisation, Horsham Chess Club. The change I needed to make was to set the width of the block to 250px, so that the content downloaded from Twitter would all be within the block’s border. However, although I could work out the ID of the block easily enough using Firebug, it was unclear where I should put the styling that I needed applied to it.

Fortunately, I was able to find an article that dealt with this topic: How to add CSS files in Drupal 7. This article identified two main techniques:

  • Using the info file to add CSS
  • Using drupal_add_css() for Modules and Themes

I decided that using the second in the module I used to create the block was best.

I first created a simple CSS file named default.css, which I placed in the module directory. This contained the following styling:

#block-twitter-widget-twitter-feed {
	width: 250px;

I then added the following at an appropriate point in my module implementation file:

	drupal_get_path('module', 'twitter_widget') . '/default.css', 
	array('group' => CSS_DEFAULT, 'type' => 'file')

This ensured that the stylesheet was added along with the widget markup.

2 Comments on Adding Stylesheets to a Drupal Module


  • Jason says:

    Can I ask a question. I am learning Drupal 7 and am trying to create a web form using a custom module. I added the css file to the module .info file and place the form.css in the same directory as the custom module. However, the css is not loaded into the web page and the web page is not using the css styles. Not knowing what to do, I copied the form.css to mail drupal 7 page, sites/all/modules directory.
    How can I debug this problem? Thank you very much.

    • James Mansson says:

      I’d start by looking at the source of the page generated. Is there a link to the stylesheet there? If there is, then that will indicate where you need to place the CSS file. A browser tool like Firebug (if you are using Firefox) can be very useful for checking what is/isn’t being loaded.

Leave a Reply

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