JSFiddle - React, Tailwind, and code Playground
by lollero
HTML
<img id="fit" src="http://i49.tinypic.com/3tqxk.jpg" />
<!--
<img id="fit" src="https://dl.dropbox.com/u/2787908/2011-08-25%2022.58.53.jpg" />
-->
CSS
#fit {
position: fixed;
visibility: hidden;
}
#fit.landscape {
width: 100%;
top: 50%;
left: 0px;
}
#fit.portrait {
height: 100%;
top: 0px;
left: 50%;
}
#fit.show {
visibility: visible;
}
JavaScript
// Images loaded plugin
// https://github.com/desandro/imagesloaded
(function(c,q){var m="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";c.fn.imagesLoaded=function(f){function n(){var b=c(j),a=c(h);d&&(h.length?d.reject(e,b,a):d.resolve(e));c.isFunction(f)&&f.call(g,e,b,a)}function p(b){k(b.target,"error"===b.type)}function k(b,a){b.src===m||-1!==c.inArray(b,l)||(l.push(b),a?h.push(b):j.push(b),c.data(b,"imagesLoaded",{isBroken:a,src:b.src}),r&&d.notifyWith(c(b),[a,e,c(j),c(h)]),e.length===l.length&&(setTimeout(n),e.unbind(".imagesLoaded",
p)))}var g=this,d=c.isFunction(c.Deferred)?c.Deferred():0,r=c.isFunction(d.notify),e=g.find("img").add(g.filter("img")),l=[],j=[],h=[];c.isPlainObject(f)&&c.each(f,function(b,a){if("callback"===b)f=a;else if(d)d[b](a)});e.length?e.bind("load.imagesLoaded error.imagesLoaded",p).each(function(b,a){var d=a.src,e=c.data(a,"imagesLoaded");if(e&&e.src===d)k(a,e.isBroken);else if(a.complete&&a.naturalWidth!==q)k(a,0===a.naturalWidth||0===a.naturalHeight);else if(a.readyState||a.complete)a.src=m,a.src=d}):
n();return d?d.promise(g):g}})(jQuery);
$(document).ready(function() {
var image = $('#fit');
function fitImage() {
image.imagesLoaded(function() {
var img = $(this);
// Check orientation.
var orientation = img.width() > img.height() ? 'landscape' : 'portrait';
// Adds a class that corresponds the orientation.
img.addClass( orientation );
// If img is landscape = margin-top: **Minus value, that is half of image height**
// If img is portrait = margin-left: **Minus value, that is half of image width**
var imgCSS = img.hasClass('landscape') ? { marginTop: -( img.height() / 2 ) } : { marginLeft: -( img.width() / 2 ) };
img.css( imgCSS ).addClass('show');
});
}
fitImage();
$(window).on("resize", fitImage );
});