6

When I use an Image Style that scales the original image, Drupal 7 (now 7.14) prints the height and width attributes in the img tag whereas before it didn't.
So before, my CSS img {max-width: 100%;} preserved the images aspect ratio when displayed in a small box (i.e. on a mobile screen), but now clashes with height and width attributes. Drupal generates enclosing boxes with no explicit height so the result is an elongated distortion.
What can I do - preferably with CSS alone, but in a template file's php if necessary - to preserve the aspect ratio?

3
  • To clarify, this problem started after you upgraded to Drupal 7.14 because img tags now specify height and width attributes? May 9, 2012 at 16:31
  • For reference, see drupal.org/node/1345744
    – mpdonadio
    May 9, 2012 at 17:11
  • @JonathanElmore Yes.
    – iainH
    May 9, 2012 at 21:24

3 Answers 3

16

It's as simple as just adding height:auto;

img {
max-width:100%;
height:auto;
}
0
4

I haven't tried it but using CSS you might just get away with:

img {max-width: 100% !important;}

If not, I think the simplest solution would be just to stop the theme_image() function from outputting the width and height attributes (in template.php as you suggest). There are couple of ways you could do this.

Firstly, you could implement hook_preprocess_image() to remove the attributes from the theme vars:

function MYTHEME_preprocess_image(&$variables) {
  foreach (array('width', 'height') as $key) {
    if (isset($variables[$key])) {
      unset($variables[$key]);
    }

    if (isset($variables['attributes'][$key])) {
      unset($variables['attributes'][$key]);
    }
  }
}

That method may have the potential to be overridden by something else in the system though. To get around that you can simply override the theme_image() function altogether (it's not a long function):

function MYTHEME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  // 'width' and 'height' have been removed here
  foreach (array('alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}
1
  • 1
    I use the theme_image() method with good results.
    – mpdonadio
    May 9, 2012 at 17:10
0

I use this technique for responsive images with fitting into its container (and aligned to whatever point in it) which is also responsive. With this technique you can make miracles. Responsive miracles.

https://stackoverflow.com/a/28073729/1663572

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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