When viewing the code below, you may notice that it displays correctly in Chrome or IE with the image set to be 200px wide. However, in Firefox and Opera, the max-width
style seems to be completely ignored. Is there a reason for this inconsistency across browsers, and what would be the best workaround to ensure compatibility? Additionally, which approach adheres most closely to web standards?
Note
In cases like these, one potential solution is to specifically define the max-width
as 200px
. Although this example is quite specific, the goal is to find a technique that works for containers with variable widths.
<!doctype html>
<html>
<head>
<style>
div { display: table-cell; padding: 15px; width: 200px; }
div img { max-width: 100%; }
</style>
</head>
<body>
<div>
<img src="http://farm4.static.flickr.com/3352/4644534211_b9c887b979.jpg" />
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec facilisis
ante, facilisis posuere ligula feugiat ut. Fusce hendrerit vehicula congue.
at ligula dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
leo metus, aliquam eget convallis eget, molestie at massa.
</p>
</div>
</body>
</html>
[Update]
A user named mVChr pointed out that according to the W3C specification, the max-width
property does not apply to inline
elements. Even after attempting
div img { max-width: 100%; display: block; }
, the issue remains unresolved.
[Update]
Despite ongoing challenges, I have resorted to a JavaScript workaround to address this issue. It essentially recreates the scenario mentioned above and tests browser support for using max-width
within display: table-cell
. (Using a data URI eliminates the need for an extra HTTP request. The one included below is a 3x3 BMP image.)
jQuery( function ( $ ) {
var img = $( "<img style='max-width:100%' src='" +
"data:image/bmp;base64,Qk1KAAAAAAAAAD4AAAAoAAAAAwAAA" +
"AMAAAABAAEAAAAAAAwAAADEDgAAxA4AAAAAAAAAAAAAAAAAAP//" +
"/wAAAAAAwAAAAKAAAAA%3D" +
"'>" )
.appendTo(
$( "<div style='display:table-cell;width:1px;'></div>" )
.appendTo( "body" )
);
$.support.tableCellMaxWidth = img.width() == 1;
img.parent().remove();
});