chacadwa.com

Technical blog and writings by Micah Webner.

Clear image size attributes in Drupal 7

The default behavior when rendering images in Drupal 7 is to include the height and width tags on images. This causes problems for responsive design, where we want to set these attributes in css, if at all. There's a historic reason why Drupal 7 includes these tags by default. It was removed at one point, and put back in, although I can't find the actual issue numbers right now.

Update 7/23/2018: It took a long time for me to realize I was doing this the hard way. Like everything else in Drupal, this can be handled by a simple theme preprocess hook. I've replaced the original post.

/**
 * Implements hook_preprocess_HOOK().
 */

function mysite_preprocess_image(&$variables) {

   // Clear size attributes before calling theme_image().
   // Setting these atributes causes problems for responsive design.
  foreach (array('width', 'height') as $key) {
    if (isset($variables[$key])) {
      unset($variables[$key]);
    }
  }
}
Topics: