Я использовал
.on('load', function () {
вместо
.each(function(){
используется в этот ответ помогает устранить проблему с пустыми значениями высоты и ширины, когда изображение еще не загружено
<style type="text/css">
.fixed-div {
position: relative;
}
.variable {
width: 100%;
height: auto;
}
.variable.js-fix {
position:absolute;
top:50%;
left:50%;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function(){
$(".fixed-div img.variable").on('load', function () {
//get height and width (unitless) and divide by 2
var hWide = ($(this).width())/2; //half the image's width
var hTall = ($(this).height())/2; //half the image's height, etc.
console.log("width", $(this).width());
console.log("height", $(this).height());
// attach negative and pixel for CSS rule
hWide = '-' + hWide + 'px';
hTall = '-' + hTall + 'px';
$(this).addClass("js-fix").css({
"margin-left" : hWide,
"margin-top" : hTall
});
});
});
</script>
<div class="fixed-div">
<img class="variable" src=""/>
</div>