7

Drupal 7.9 re-introduces height and width attributes to images - I understand this helps improve front-end performance, but it's giving me problems while using flexible images in the vein of responsive web design.

This is the same issue as whitefleaCH mentioned on this post: How can I prevent height/width attributes on images run through the theme system?

Using max-width in CSS still scales images, however the height remains as what was defined in the markup. Does anyone know how to either correct this in CSS or remove the height/width attributes from images all together?

6

Check out theme_image():

foreach (array('width', 'height', 'alt', 'title') as $key) {
  if (isset($variables[$key])) {
    $attributes[$key] = $variables[$key];
  }
}
return '<img' . drupal_attributes($attributes) . ' />';

So you need to clean width and height as top level keys but also from the attributes array:

function mymodule_preprocess_image(&$variables) {
  unset(
    $variables['width'],
    $variables['height'],
    $variables['attributes']['width'],
    $variables['attributes']['height']
  );
}

And yes, in Drupal 7, Variable process functions can now be used for all theming hooks. Don't forget to clear your cache so the new preprocess function is picked up.

2
function YOUR_THEMENAME_image($vars) {
  $attributes = $vars['attributes'];
  $attributes['src'] = file_create_url($vars['path']);

  // remove width and height attributes
  foreach (array('alt', 'title') as $key) {
    if (isset($vars[$key])) {
      $attributes[$key] = $vars[$key];
    }
  }
  return '<img' . drupal_attributes($attributes) . ' />';
}
2

You might be interested in checking out the Adaptive Image module:

The Adaptive image module provides device-appropriate versions of images from your fields. You can activate adaptive images by adding an adaptive effect to any of your image styles.

1

In CSS overriding the currently defined height by setting height to 'auto' should do the trick.

  • 1
    I agree. This is the simplest and most effective way to fix this IMHO. Just add img{height:auto;} – user842 Jan 8 '12 at 18:42
  • 1
    This is an effective way, however it breaks in IE 8 and below! – splatio Mar 15 '12 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.