JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<img class="max_width" src="http://www.crummy.com/photos/2006/06-Worcester/09-The%20Foo%20Bar.jpg" alt="foobar" />
</div>
CSS
div
{
height: 150px;
width: 50%;
border: 1px solid red;
position: relative;
}
img
{
margin: 0px auto;
border: 1px solid blue;
display: block;
}
.max_width
{
max-width: 80%;
}
JavaScript
$('img').bind('load', function()
{
var margin_left = 0;
var width = 0;
var max_width = $(this).css('max-width');
$(this).fadeTo(0, 0.01, function()
{
setMargin();
margin_left = $(this).position().left;
width = $(this).width();
// remember to set the opacity back to full...
$(this).fadeTo(0, 1);
// hide it so that the image can blind in for the first time...
$(this).hide();
// set it up for blinding...
$(this).css('width', width + 'px');
$(this).css('margin-left', margin_left + 'px');
$(this).removeClass('max_width');
// blind in...
$('img').show('blind', 2000, function()
{
// reset the image to original state...
$(this).css('width', '');
$(this).css('margin-left', '');
$(this).addClass('max_width');
});
});
});
console.log('img: ' + $('img').height());
console.log('div: ' + $('div').height());
function setMargin() {
var marginTop =
( $('img').closest('div').height()
- $('img').height() ) / 2;
console.log('marginTop: ' + marginTop);
$('img').css('marginTop', marginTop + 'px');
}