2

I have a problem with display of img in the table:

<table>
<tr>
<td>
    <div>    
        <img src="https://www.google.ru/images/srpr/logo4w.png"/>
        <img src="http://pictar.ru/data/media/24/nature__463_.jpg"/>
    </div>
    </td>
</tr>
</table>

with css:

div {
    height: 100%;
    width: 100%;
    border:2px solid red;
}
div img {
    max-width: 100%;
    max-height: 100%;
}

JS Fiddle example.
In Chrome both images scaling proportionally to div-wrapper, but in Firefox and IE9 images do not scale.

How can I get Chrome behaviour everywhere?

ANSWER: The only solution is to use javascript. My cross-browser solution is: http://jsfiddle.net/TAE3w/21/

SerCe
  • 5,826
  • 2
  • 32
  • 53

3 Answers3

3

You simply need to set the width to 100% also.

div img {
    width: 100%;
    max-width: 100%;
    max-height: 100%;
}

http://jsfiddle.net/samliew/TAE3w/9/

The most consistent effect on all three browsers would be:

div img {
    display: block;
    width: 100%;
    height: auto;
    max-width: 100%;
    max-height: 100%;
}

http://jsfiddle.net/samliew/TAE3w/15/

See related questions:

Community
  • 1
  • 1
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
  • 1
    But in this case Google image scaling wider than it actually is – SerCe Mar 01 '13 at 08:50
  • It is interesting, but my issue is to make the behavior of all three browsers in the same way as the first example in chrome, my problem particularly described [stackoverflow](http://stackoverflow.com/questions/2923710/why-do-firefox-and-opera-ignore-max-width-inside-of-display-table-cell), but solutions do not works for me – SerCe Mar 01 '13 at 09:07
1

In Firefox max-width doesn't work if specified as percentage but works if given an exact value. Use javascript to set maxWidth to image width. No wrapper is needed.

<img onload="this.style.maxWidth=(this.getAttribute('width')?this.getAttribute('width'):this.naturalWidth).toString() + 'px'; this.style.width='100%'; this.style.height='auto';" src="yourimage.jpg" />

If you don't want to change the image tag use a javascript funtction on all images.

function makeImagesResponsive(){
    var images = document.getElementsByTagName('img');
    for(var i = 0; i < images.length; ++i) {
        images[i].style.maxWidth=(images[i].getAttribute('width')?images[i].getAttribute('width'):images[i].naturalWidth).toString() + 'px';
        images[i].style.width='100%';
        images[i].style.height='auto';  
    }
}
window.addEventListener( "load", makeImagesResponsive, false );

Of course you can select only images from specific sections of your web site, or filter them by class name or other attribute.

Sorin
  • 221
  • 2
  • 4
0

For the record, support for max-width on a table recently landed in Chrome.

I'm not sure if the fix was applied to Webkit, or just Chrome's Blink engine. The problem still affects Safari 6.

Paul Gordon
  • 2,532
  • 3
  • 26
  • 24